题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb?tpId=37&tqId=21290&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=3&judgeStatus=undefined&tags=&title=
import sys ops = ["+", "-", "*", "/"] # 从四个数中任意挑俩数,计算结果放回去,变成仨数 # 从三个数中任意挑俩数,计算结果放回去,变成俩数 # 最后俩数执行运算 def cal(a, b, op): if op == "+": return a+b elif op == "-": return a-b elif op == "*": return a*b elif op == "/": if b == 0: return 0 else: return a/b def dfs(nums): n = len(nums) if n == 1: return nums[0] for i in range(n): for j in range(n): if i != j: for op in ops: # 首先挑出两个数进行计算 nums_copy = [cal(nums[i], nums[j], op)] for k in range(n): if k != i and k != j: nums_copy.append(nums[k]) # 计算完毕重新进入计算 if dfs(nums_copy) == 24: return 24 return 0 for line in sys.stdin: nums = list(map(int, line.strip().split(" "))) print("true" if dfs(nums) == 24 else "false")