问题 1:为什么要按照以下顺序组合字母,stored_characters = ''.join(unique_characters)行不行,只是顺序不同
stored_characters = ''.join(first_letters) + \
''.join(unique_characters - first_letters)
问题 2: 为什么要排除前 n 个元素含有 zero 的排列?
if zero not in guess[:n]:
代码如下:
import re
import itertools
def solve(puzzle):
words = re.findall('[A-Z]+', puzzle.upper())
unique_characters = set(''.join(words))
assert len(unique_characters) <= 10, 'Too many letters'
first_letters = {word[0] for word in words}
n = len(first_letters)
stored_characters = ''.join(first_letters) + \
''.join(unique_characters - first_letters)
characters = tuple(ord(c) for c in stored_characters)
digits = tuple(ord(c) for c in '0123456789')
zero = digits[0]
for guess in itertools.permutations(digits, len(characters)):
if zero not in guess[:n]:
equation = puzzle.translate(dict(zip(characters,guess)))
if eval(equation):
return equation
if __name__ == '__main__':
import sys
for puzzle in sys.argv[1:]:
print(puzzle)
solution = solve(puzzle)
if solution:
print(solution)
1
dreampython OP 自问自答(个人理解):
问题 1:将 first_letters 放在前面是问题 2 的伏笔 问题 2:排除前 n 个元素含有 zero 的排列,就是排除问题 1 中被排在前面的 first_letters 这些字符对应的数字不能为 0 |
2
myhyperion 2018-03-16 16:28:46 +08:00
我已有这个疑问,后来发现
<code> >>> 01+1==2 SyntaxError: invalid token </code> |