超强!略微简练一些的代码

来源: chirolike 2016-01-06 13:42:29 [] [博客] [旧帖] [给我悄悄话] 本文已被阅读: 次 (1296 bytes)
本文内容已被 [ chirolike ] 在 2016-01-06 15:00:33 编辑过。如有问题,请报告版主或论坛管理删除.
回答: 用Python解决一道小学数学题在城里2016-01-05 20:01:05
import itertools
import re

BAD_LIST        = ['55', '5(', ')(', ')5', '(5)']
FIRST_CHAR_LIST = ['(', '-', '5']
LAST_CHAR_LIST  = [')', '5']
exp_list        = []
my_list         = [r for r in itertools.product(FIRST_CHAR_LIST, LAST_CHAR_LIST)]
init_lst        = ['5', '5', '5', '5', '5', '+', '-', '*', '/', '(', ')']

if  __name__ == '__main__':
    print '======= Possible combinations for the math question ============'
    for first, last in my_list:
        lst = list(init_lst)
        lst.remove(first)
        lst.remove(last)
        for exp in [first + ''.join(f) + last for f in itertools.permutations(lst)]:
            if  any([y in exp for y in BAD_LIST]) or\
                re.search(r'[-*/+][-*/+]+|^\(.*\)$', exp): continue
            elif exp not in exp_list:
                try:
                    print "%s = %d" % (exp, eval(exp))
                    exp_list.append(exp)
                except: pass
    print 'Total expressions found = ', len(exp_list)

所有跟帖: 

的确简洁多了,赞! -在城里- 给 在城里 发送悄悄话 在城里 的博客首页 (0 bytes) () 01/06/2016 postreply 18:42:05

请您先登陆,再发跟帖!

发现Adblock插件

如要继续浏览
请支持本站 请务必在本站关闭/移除任何Adblock

关闭Adblock后 请点击

请参考如何关闭Adblock/Adblock plus

安装Adblock plus用户请点击浏览器图标
选择“Disable on www.wenxuecity.com”

安装Adblock用户请点击图标
选择“don't run on pages on this domain”