如何为顺序固定的4个数字计算所有加减乘除运算组合以得到结果10?
固定顺序数字运算组合匹配目标值的解决方案
核心思路
这类问题的本质是枚举所有可能的运算符组合与运算优先级,因为数字顺序固定,只需聚焦两个关键点:
- 相邻数字间的运算符选择(+、-、×、÷)
- 通过括号改变运算优先级的所有可能
步骤拆解
- 枚举运算符组合:4个数字有3个运算符位置,每个位置4种选择,共4³=64种组合。
- 覆盖所有运算优先级:4个数字的运算顺序有5种不同的括号组合(即优先级情况),需全部遍历:
- ((a op1 b) op2 c) op3 d
- (a op1 (b op2 c)) op3 d
- a op1 ((b op2 c) op3 d)
- a op1 (b op2 (c op3 d))
- (a op1 b) op2 (c op3 d)
- 计算与验证:对每种运算符+优先级的组合计算结果,判断是否等于目标值,同时处理除法的除数为0和浮点精度问题。
实现代码(Python)
from itertools import product # 输入参数 nums = [1, 5, 3, 8] target = 10 operators = ['+', '-', '*', '/'] # 运算处理函数 def compute(a, op, b): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b elif op == '/': if b == 0: return None # 跳过除数为0的情况 return a / b # 遍历所有运算符组合 for op1, op2, op3 in product(operators, repeat=3): # 情况1: ((a op1 b) op2 c) op3 d res = compute(compute(compute(nums[0], op1, nums[1]), op2, nums[2]), op3, nums[3]) if res is not None and abs(res - target) < 1e-9: print(f"(({nums[0]} {op1} {nums[1]}) {op2} {nums[2]}) {op3} {nums[3]} = {target}") # 情况2: (a op1 (b op2 c)) op3 d res = compute(compute(nums[0], op1, compute(nums[1], op2, nums[2])), op3, nums[3]) if res is not None and abs(res - target) < 1e-9: print(f"({nums[0]} {op1} ({nums[1]} {op2} {nums[2]})) {op3} {nums[3]} = {target}") # 情况3: a op1 ((b op2 c) op3 d) res = compute(nums[0], op1, compute(compute(nums[1], op2, nums[2]), op3, nums[3])) if res is not None and abs(res - target) < 1e-9: print(f"{nums[0]} {op1} (({nums[1]} {op2} {nums[2]}) {op3} {nums[3]}) = {target}") # 情况4: a op1 (b op2 (c op3 d)) res = compute(nums[0], op1, compute(nums[1], op2, compute(nums[2], op3, nums[3]))) if res is not None and abs(res - target) < 1e-9: print(f"{nums[0]} {op1} ({nums[1]} {op2} ({nums[2]} {op3} {nums[3]})) = {target}") # 情况5: (a op1 b) op2 (c op3 d) res = compute(compute(nums[0], op1, nums[1]), op2, compute(nums[2], op3, nums[3])) if res is not None and abs(res - target) < 1e-9: print(f"({nums[0]} {op1} {nums[1]}) {op2} ({nums[2]} {op3} {nums[3]}) = {target}")
关键注意点
- 浮点精度处理:除法会产生浮点数,判断结果是否等于目标值时,需通过差值绝对值小于极小值(如1e-9)避免精度误差。
- 除数为0规避:必须在除法运算前检查除数是否为0,防止抛出异常。
- 扩展适配:若数字数量超过4个,手动枚举优先级会很繁琐,可改用递归方式拆分数字区间,枚举所有可能的运算顺序。
内容的提问来源于stack exchange,提问作者Saber Heydari
相关产品推荐
相关产品推荐

