题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
学习了这位大佬的思路https://blog.nowcoder.net/n/ecc7958961ea4037b488fddb34fd70ee?f=comment,在此基础上考虑了括号的使用情况。
import itertools def noPara(arr, y): lis = [y] for i in arr: lis.append(i) lis.append(i + y) lis.append(i - y) lis.append(i*y) lis.append(i/y) return lis def para(a, b, c, d): ans1 = (a + b) * (c + d) ans2 = (a + b) * (c - d) ans3 = (a - b) * (c + d) ans4 = (a - b) * (c - d) return [ans1, ans2, ans3, ans4] num_list = [int(i) for i in input().split(' ')] judge = 0 for i in range(len(list(itertools.permutations(num_list)))): a, b, c, d = list(itertools.permutations(num_list))[i] lis1 = noPara([a], b) lis2 = noPara(lis1, c) lis3 = noPara(lis2, d) lis3.extend(para(a, b, c, d)) if 24 in lis3: print('true') judge = 1 break if judge == 0: print('false')