代碼在這裏:

來源: 2016-01-07 19:45:35 [博客] [舊帖] [給我悄悄話] 本文已被閱讀:

import re, itertools

exp_list = []
OPS_LIST = ['+','*']    # operators allowed
ANSWER = 69

if __name__ == '__main__':
    print '======= Possible combinations for the math question ============'
    for op in itertools.product( OPS_LIST, repeat = 9):
        exp = ''.join( [ item for pair in zip([str(x) for x in range(0, 10)],  \
            list(op) + [0]) for item in pair][:-1])
        try:
            result = eval(exp)
            if result == ANSWER and (exp not in exp_list):
                exp_list.append(exp)
                print '%s = %d' % (exp, result)
        except: pass        
    print 'Total expressions found = ', len(exp_list)