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)
超强!略微简练一些的代码
本文内容已被 [ chirolike ] 在 2016-01-06 15:00:33 编辑过。如有问题,请报告版主或论坛管理删除.