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

本帖于 2016-01-06 15:00:33 时间, 由普通用户 chirolike 编辑
回答: 用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

请您先登陆,再发跟帖!