题解 | 24点游戏算法

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

from itertools import permutations, product

"""permutations 求全排列"""
"""product 求集合笛卡尔集(求组合) repeat"""

# 24点游戏,遍历所有可能
nums = list(map(int, input().split()))


def solve_24(nums):
    # 定义四则运算函数
    def calculate(a, b, op):
        if op == '+':
            return a + b
        elif op == '-':
            return a - b
        elif op == '*':
            return a * b
        elif op == '/':
            if b == 0:  # 避免除零错误
                return None
            return a / b
        return None

    # 递归检查所有可能的运算组合 顺序执行就行
    def check(nums, ops):
        if len(nums) == 1:
            # 检查是否接近24(考虑浮点数精度)
            return abs(nums[0] - 24) < 1e-6
        for i in range(len(nums) - 1):
            a, b = nums[i], nums[i + 1]
            op = ops[i]
            res = calculate(a, b, op)
            if res is None:  # 如果运算无效(如除零),跳过
                continue
            # 生成新的数字和运算符列表
            new_nums = nums[:i] + (res,) + nums[i + 2:]
            new_ops = ops[:i] + ops[i + 1:]
            if check(new_nums, new_ops):
                return True
        return False

    # 遍历所有数字排列和运算符组合
    for num_perm in permutations(nums):  # permutation求全 排列
        for ops in product('+-*/', repeat=3):  # 3个运算符 product求全 组合
            if check(num_perm, ops):
                return True
    return False


res = solve_24(nums)
if not res:
    print('false')
else:
    print('true')

24点总共4个数字,共24种排列,3个符号组合,4*4*4共64种组合。所以无非24*64=1536种不同方式。直接遍历所有可能。这里使用permutation求全排列和product求全组合是python独特的优势了。

全部评论

相关推荐

无一技之长怎么办:别去右边,售前,实施,需求分析一起,这是把人当牛马用啊,快跑,这些岗位天花板很低的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务