Python中如何实现24点游戏


Python中如何实现24点游戏
2 回复

帖子标题:Python中如何实现24点游戏

24点游戏的核心是穷举所有可能的运算组合。这里提供一个完整的实现,使用递归和运算符枚举。

import itertools
import operator

def solve_24(nums):
    """
    解决24点问题,返回所有能得到24的表达式
    """
    ops = [('+', operator.add), ('-', operator.sub), 
           ('*', operator.mul), ('/', operator.truediv)]
    solutions = []
    
    def dfs(nums, expr):
        if len(nums) == 1:
            # 检查结果是否接近24(考虑浮点误差)
            if abs(nums[0] - 24) < 1e-10:
                solutions.append(expr[0])
            return
        
        # 从当前数字中任选两个进行组合
        for i, j in itertools.combinations(range(len(nums)), 2):
            a, b = nums[i], nums[j]
            exp_a, exp_b = expr[i], expr[j]
            
            # 剩余的数字
            remaining_nums = [nums[k] for k in range(len(nums)) if k not in (i, j)]
            remaining_expr = [expr[k] for k in range(len(expr)) if k not in (i, j)]
            
            # 尝试所有运算符
            for op_symbol, op_func in ops:
                # 加法和乘法满足交换律,避免重复计算
                if op_symbol in ('+', '*') and i > j:
                    continue
                
                # 除法分母不能为0
                if op_symbol == '/' and abs(b) < 1e-10:
                    continue
                
                try:
                    # 计算新值
                    new_val = op_func(a, b)
                    # 构建新表达式(考虑优先级加括号)
                    if op_symbol in ('+', '-'):
                        new_exp = f'({exp_a}{op_symbol}{exp_b})'
                    else:
                        new_exp = f'{exp_a}{op_symbol}{exp_b}'
                    
                    # 递归处理
                    dfs(remaining_nums + [new_val], 
                        remaining_expr + [new_exp])
                except ZeroDivisionError:
                    continue
    
    # 初始表达式就是数字本身
    init_expr = [str(num) for num in nums]
    dfs(nums, init_expr)
    return solutions

# 使用示例
if __name__ == "__main__":
    # 测试用例
    test_cases = [
        [4, 4, 6, 6],
        [1, 3, 4, 6],
        [3, 3, 8, 8],
        [1, 5, 5, 5]
    ]
    
    for nums in test_cases:
        print(f"数字 {nums}:")
        solutions = solve_24(nums)
        if solutions:
            for sol in solutions[:3]:  # 只显示前3个解
                print(f"  {sol} = 24")
        else:
            print("  无解")
        print()

代码说明:

  1. 核心算法:深度优先搜索(DFS)递归地组合数字和运算符
  2. 运算符处理:支持加减乘除四种运算,处理除零异常
  3. 表达式构建:自动添加括号保证运算顺序正确
  4. 去重优化:利用交换律减少重复计算
  5. 浮点精度:使用1e-10容差处理浮点运算误差

运行示例:

数字 [4, 4, 6, 6]:
  (4+4)*(6-6) = 24
  4*4+6+6 = 24
  4*(4+6)-6 = 24

数字 [1, 3, 4, 6]:
  6/(1-3/4) = 24
  6/((1-3)/4) = 24

总结: 用DFS穷举所有运算组合就能解决24点问题。


You’re wrong, one of the solutions is (7 * 7) / (8 - 6).

回到顶部