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)
超強!略微簡練一些的代碼
本帖於 2016-01-06 15:00:33 時間, 由普通用戶 chirolike 編輯