题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
解题思路:
1. 操作符与括号的选择:
需要考虑加、减、乘、除这四种基本运算符号。同时,由于运算的顺序不同,括号的使用也可能影响最终结果。因此,必须尝试各种组合和排列方式来进行计算。
2. 数字排列的组合:
给定的4个数字可以有不同的排列方式,总共有24种排列方式(4! = 24)。我们需要尝试这些不同的数字排列组合。
3. 运算符的选择:
在每一组排列的数字之间插入运算符,这意味着有3个位置可以选择运算符,因此运算符有4种(加减乘除),总共有4^3 = 64 种运算符的组合方式。
4. 括号的组合:
括号的加入会改变运算的顺序,因此需要考虑不同的括号位置。例如:((a op b) op c) op d 和 (a op (b op (c op d))) 都是不同的表达式形式。
import itertools 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 float('inf') return a / b def evaluate_expression(nums): operators = ['+', '-', '*', '/'] # 尝试所有数字排列组合 for perm in itertools.permutations(nums): # 尝试所有操作符的排列组合 for ops in itertools.product(operators, repeat=3): # 使用不同的括号组合计算 try: # (a op1 b) op2 (c op3 d) if abs(cal(cal(perm[0], perm[1], ops[0]), cal(perm[2], perm[3], ops[2]), ops[1]) - 24) < 1e-6: return True # ((a op1 b) op2 c) op3 d if abs(cal(cal(cal(perm[0], perm[1], ops[0]), perm[2], ops[1]), perm[3], ops[2]) - 24) < 1e-6: return True # (a op1 (b op2 c)) op3 d if abs(cal(cal(perm[0], cal(perm[1], perm[2], ops[1]), ops[0]), perm[3], ops[2]) - 24) < 1e-6: return True # a op1 ((b op2 c) op3 d) if abs(cal(perm[0], cal(cal(perm[1], perm[2], ops[1]), perm[3], ops[2]), ops[0]) - 24) < 1e-6: return True # a op1 (b op2 (c op3 d)) if abs(cal(perm[0], cal(perm[1], cal(perm[2], perm[3], ops[2]), ops[1]), ops[0]) - 24) < 1e-6: return True except ZeroDivisionError: continue return False # 输入与输出部分 def main(): # 读入4个[1,10]的整数 nums = list(map(int, input().split())) # 输出能否得到24点 if evaluate_expression(nums): print("true") else: print("false") if __name__ == "__main__": main()