Python - 字母算术谜题
2016-04-30 00:34
423 查看
如: SEND + MORE == MONEY
9567 + 1085 == 10652
字母和数字一一对应
首字母不为0
几点说明:
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
相关文章推荐
- Python str内部功能介绍
- python 多线程 join 的 细节问题 注意使用事项
- Python开发环境配置
- 如何在MAC 指定文件夹打开终端(terminal)
- python 函数超时装饰器
- python 正则表达式
- python web中models.py中的一些处理
- win下python和opencv安装
- python解决网站的反爬虫策略
- python3.5使用pip安装scrapy时unable to find vcvarsall.bat异常处理
- knn算法python实现
- python解决八皇后问题
- Regular Expression Python
- 基于python的爬虫---自顶向下的设计思想
- python学习5
- windows环境下把Python代码打包成独立执行的exe可执行文件
- python算法基础
- 武sirpython第二讲(1)运算符
- sublime text3里搭建python
- Python生成二维码脚本