问题描述
给出任意个整数,寻找其可能的组合,使其四则运算结果值为24点
解决方案
使用分治思想,每次取两个数字运算,将其结果替换数集中已使用的操作数,直到融合为一个计算式,判断其是否符合条件
该问题解决过程用到了穷举法,如果结果不唯一,则会输出所有可能结果
nums = ['3', '3', '7', '7']
opts = ['({}+{})', '({}-{})', '{}*{}', '{}/{}']
rsts = set()
def calc(nums):
count = len(nums)
if count == 1:
try:
if eval(nums[0]) == 24:
rsts.add('{} = 24'.format(nums[0]))
finally:
return
for i in range(count):
for j in range(count):
if i == j:
continue
for opt in opts:
nums_n = [nums[x] for x in range(len(nums)) if x not in (i, j)]
opt_str = opt.format(nums[i], nums[j])
nums_n.append(opt_str)
calc(nums_n)
calc(nums)
for rst in rsts:
print(rst)
输出结果为:
(3+3/7)*7 = 24
7*(3/7+3) = 24
(3/7+3)*7 = 24
7*(3+3/7) = 24