如: 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.permutations(iterable, r=None) -> 返回 从iterable中取出r个元素的有序组合 的迭代器
例如: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.translate(map) -> 按照map的对应关系进行字符替换
map 一般为一个字典,其键和值都是ASCII字符的十进制表示,
例如 "abc123".translate({97:65, 98:97}) -> 'Aac123'
map可以通过str.maketrans()生成
例如:str.maketrans('123', 'abc') -> {49: 97, 50: 98, 51: 99}
本例中是通过ord、zip、dict的方式生成的
zip(*iterables) -> 返回一个元组迭代器,
例如: list( zip([1,2,3], 'abc') ) -> [(1, 'a'), (2, 'b'), (3, 'c')]
list( zip('ABC', 'xy') ) -> [('A','x'), ('B', 'y')] 以少的为准
ord(string) -> int
例如: ord('a') -> 97 ord('1') -> 49
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