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) sorted_characters = ''.join(first_letters) + \ ''.join(unique_characters - first_letters) characters = tuple(ord(c) for c in sorted_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__':
1.返回匹配正则表达式的列表元素
2.列表元素集合
3.python断言,AssertionError 异常时提供可读信息
4.列表元素首字母集合 (Curly braces { } or the set() function can be used to create sets)
5.首字母集合长度
6.重排puzzle集合中元素,组成首字母在前的字符串
7.生成器表达式传给tuple()函数,进行迭代组成元组
8.同上
9.根据len排列序列digits,permutations() 函数返回迭代器
10.判断0是否对应puzzle列表元素首字符
11.将出现在转换表中的键的字节转换为它对应的值的字节
12.调用python通用求值工具eval(),进行判断表达式是否有效
参考文章:http://woodpecker.org.cn/diveintopython3/advanced-iterators.html#string-translate 深入python