题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb
# 基本上已考虑所有情况,包括各种运算顺序和带括号的情况
arr = input().split()
def check_24(arr, exp=""):
if len(arr) == 1:
exp += arr[0]
# 找出3个运算符所在位置
flag = 0
for i in range(len(exp)):
if not exp[i].isdigit() and flag == 0:
flag = 1
s0 = i
continue
if not exp[i].isdigit() and flag == 1:
flag = 2
s1 = i
continue
if not exp[i].isdigit() and flag == 2:
s2 = i
break
for exp_ in [ # 考虑各种带括号的形式,这里有很大优化空间,但是踩坑已经踩到吐血不想深究了
exp, # a + b + c + d
f"({exp[:s1]}){exp[s1:]}", # (a + b) * c + d
f"{exp[:s1+1]}({exp[s1+1:]})", # a + b * (c + d)
f"({exp[:s1]}){exp[s1]}({exp[s1+1:]})", # (a + b) * (c + d)
f"({exp[:s2]}){exp[s2:]}", # (a + b + c) * d
f"{exp[:s0+1]}({exp[s0+1:]})", # a * (b + c + d)
]:
# 执行表达式,用try跳过/0的情况
try:
locals()["res"] = 0
exec(f"res={exp_}")
except:
pass
if round(locals()["res"], 5) == 24: #保留5位小数,使类似23.99999...这种结果可以通过
# print(exp_)
raise # 结果等于24就raise直接跳出
else:
# 生成所有表达式
for i in range(len(arr)):
check_24(arr[:i] + arr[i + 1 :], exp + arr[i] + "+")
check_24(arr[:i] + arr[i + 1 :], exp + arr[i] + "-")
check_24(arr[:i] + arr[i + 1 :], exp + arr[i] + "*")
check_24(arr[:i] + arr[i + 1 :], exp + arr[i] + "/")
try:
check_24(arr)
print("false")
except:
print("true")