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

来源: 2016-01-06 13:42:29 [博客] [旧帖] [给我悄悄话] 本文已被阅读:
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)