题解 | #24点# 直接遍历须全排列关键字 优化后舒服了
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import itertools def compute(s1_list,s2): out = [] for cmp in ['+','-','*','/']: for s1 in s1_list: out.append('('+s1+cmp+s2+')') return out a,b,c,d = input().split() #取两个运算 compute_s = [] for x1,x2,x3,x4 in itertools.permutations([a,b,c,d]): temp = compute([x1],x2) compute_s.extend(compute(compute(temp,x3),x4)) for res in compute([x3],x4): compute_s.extend(compute(temp,res)) flag = "false" for cs in compute_s: try: if eval(cs) == 24: flag = "true" break #有除零得排除 except: pass print(flag)
优化了一下 既然全排列了可以不考虑 小数情况 比如 7/5*10+10 这种会在7*10/5+10 这里遍历到 然后把除零一起提前去掉
import itertools def compute(n1_list, n2_list): out = [] for i in n1_list: for j in n2_list: out.extend([i+j, i-j, i*j]) if j != 0 and i % j == 0: out.append(i/j) return out a, b, c, d = map(int, input().split()) compute_s = [] for x1, x2, x3, x4 in itertools.permutations([a, b, c, d]): # 取两个运算 temp1 = compute([x1], [x2]) # 再一个一个算 temp2 = compute(temp1, [x3]) compute_s.extend(compute(temp2, [x4])) # 再两个两个算 temp2 = compute([x3], [x4]) compute_s.extend(compute(temp1, temp2)) flag = "false" for res in compute_s: if res == 24: flag = "true" break print(flag)