题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
def judge24(nums): if len(nums) == 1: return abs(nums[0] - 24) < 1e-6 # 检查结果是否接近24(考虑浮点数精度) # 尝试所有可能的运算组合 for i in range(len(nums)): for j in range(len(nums)): if i != j: newNums = [nums[k] for k in range(len(nums)) if i != k != j] # 选择不参与当前运算的数字 for op in ['+', '-', '*', '/']: # 尝试加减乘除 if (op == '+' or op == '*') and j > i: continue # 避免重复计算,比如避免 1+3 和 3+1 重复 if op == '/' and nums[j] == 0: continue # 避免除零错误 if op == '+': newNums.append(nums[i] + nums[j]) elif op == '-': newNums.append(nums[i] - nums[j]) elif op == '*': newNums.append(nums[i] * nums[j]) elif op == '/': newNums.append(nums[i] / nums[j]) if judge24(newNums): return True newNums.pop() # 回溯,移除尝试的结果 return False # 读取4个数字 numbers = list(map(int, input().split())) # 调用函数判断是否能得到24 result = judge24(numbers) if result: print("true") else: print("false")