Python - 字母算术谜题

如: 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

  

 

 

 

 

 


 

转载于:https://www.cnblogs.com/roronoa-sqd/p/5447943.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值