这是一个小学生奥数题
使用python解:
一种方式,使用全排列方式找出
import itertools
ops = [["+","-",""]]*8
eightops=list(itertools.product(*ops))
snum=[str(i) for i in range(1,10)]
k=0
for i in range(len(eightops)):
xch = snum[0]
for j in range(8):
xch = xch + eightops[i][j] + snum[j+1]
if eval(xch) == 100 :
k = k + 1
print(f"{k:<5}{xch}")
if eval("-" + xch) == 100:
k = k + 1
print(f"{k:<5}-{xch}")
一种方式,使用回溯组合的方式:
i = 1
def sum_for_100(pattern):
global i
if len(pattern) == 17:
try:
e = ''.join(pattern)
if eval(e) == 100 :
print(i, e)
i=i+1
if eval("-" + e) == 100:
print(i, "-" + e)
i=i+1
except Exception as e:
pass
else:
x = int(pattern[-1])
for czf in ['+','-','']:
pattern.append(czf)
pattern.append(str(x + 1))
sum_for_100(pattern)
pattern.pop(-1)
pattern.pop(-1)
sum_for_100(['1'])
哪种更好呢?