如: SEND + MORE == MONEY
9567 + 1085 == 10652
- 字母和数字一一对应
- 首字母不为0
解法:
import re from itertools import permutations def solve(puzzle): puzzle= puzzle.upper() words = re.findall('[A-Z]+', puzzle) 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(str(c)) for c in range(10)) zero = digits[0] for guess in 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__': puzzle = "send + more == money" try: print(puzzle.upper()) solution = solve(puzzle) if solution: print(solution) else: print("Nothing match this") except Exception as e: print("Error: "+str(e))
几点说明:
itertools.permutationsiterable, r=None 例如:list( permutations([1,2,3], 2) ) -> [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
类似的 itertools.combinations(iterable, r=None) -> 有序组合
例如:list( combinations([1,2,3], 2) ) -> [(1, 2), (1, 3), (2, 3)]
str.translatemap
eval(expression, globals=None, locals=None) -> 把expression字符串解析为Python表达式(就是相当于去掉最外面一层引号)
例如 eval('1+1') -> 2 、 eval('1+1==2') -> True 、 eval('"1+1"') -> "1+1"
repr(object) 和eval正好相反,给对象加上一层引号 一般有 eval(repr(object)) == object
exec(object) 执行存储在字符串中的Python语句
例如 exec('print("Hello")') -> Hello