上小学的儿子问了我这么一道数学题:
1) 使用+,-,×,/,(,和)六个操作符;
2) 使用操作数5,5,5,5,5;
3) 要求每个操作数/操作符只使用一次。
列出所有可能的表达式,并计算每个表达式的值。
【注意】要排除诸如 +-,()或55这种操作数/操作符连一起的情况;也要排除5(,)(,)5,(5)等情况。
【脚本】版本使用python2.7x。演示脚本如下:
【运行结果】 共找到 210 表达式:
(5+5-5*5)/5 = -3
(5+5-5/5)*5 = 45
(5+5-5)*5/5 = 5
(5+5-5)/5*5 = 5
(5+5*5-5)/5 = 5
(5+5*5/5)-5 = 5
(5+5*5)-5/5 = 29
(5+5*5)/5-5 = 1
(5+5/5-5)*5 = 5
(5+5/5*5)-5 = 5
(5+5/5)-5*5 = -19
(5+5/5)*5-5 = 25
(5+5)-5*5/5 = 5
(5+5)-5/5*5 = 5
(5+5)*5-5/5 = 49
... (省略) ...
看来,脚本还是可以帮着干不少活的^_^。
在城里 2016.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)
链接在这里: http://bbs.wenxuecity.com/computer/241769.html