题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
用循环,没有用递归。
def gen(a):
b = len(a)
for i in range(0, b):
c = a[:]
num1 = c.pop(i)
for j in range(0, b - 1):
d = c[:]
num2 = d.pop(j)
yield d + [num1 + num2]
yield d + [num1 - num2]
yield d + [num1 * num2]
if not (abs(num2) < 1e-6):
yield d + [num1 / num2]
'''
b = gen([1,2,3])
for i in b:
print(i)
'''
o = input()
a = list(map(int, o.split()))
def check(a):
gen_list = [gen(a)]
while len(gen_list):
try:
res = next(gen_list[-1])
if len(res) == 1:
if abs(res[0] - 24) < 1e-6:
return 'true'
break
else:
gen_list.append(gen(res))
except StopIteration:
gen_list.pop(-1)
return 'false'
print(check(a))

