题解 | 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独特的优势了。

全部评论

相关推荐

05-30 13:04
已编辑
门头沟学院 算法工程师
智谱和米哈游都是ai大模型agent的业务钱的话还是米更多,几乎翻倍了,有没有老哥是两个公司其中一个的,能问问转正率咋样嘛,我问的hr回答都是做的好就可以转正暑期实习
码农索隆:选米哈游:短期高薪、敢承担风险、具备强创新能力,且愿押注游戏AI赛道。 选智谱:稳定性与行业通用能力积累,接受薪资差距以换取更稳妥的职业基础。
投递北京智谱华章科技等公司7个岗位 > 实习期间如何提升留用概率?
点赞 评论 收藏
分享
xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务