24点游戏算法题解
https://www.nowcoder.com/share/jump/9119441091689299014223
# 解决热门分享中没有考虑到所有情况的BUG 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 locals()["res"] == 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")