题解 | #24点游戏算法#

24点游戏算法

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

import itertools
# 定义四种基本运算符的函数
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return None
    return a / b
def can_get_24_recursive(numbers):
    if len(numbers) == 1:
        # 如果只剩下一个数字,检查该数字是否等于24
        return abs(numbers[0] - 24) < 1e-6

    # 生成所有可能的数字排列
    permutations = itertools.permutations(numbers)

    for perm in permutations:
        a, b, *rest = perm

        # 递归地处理剩下的数字
        for op in [add, subtract, multiply, divide]:
            if op == divide and abs(b) < 1e-6:
                continue  # 避免除以零

            result = can_get_24_recursive([op(a, b)] + rest)
            if result:
                return True

    return False

# 输入四个整数
input_numbers = [int(x) for x in input().split()]

# 检查是否可以得到24点并输出结果

if can_get_24_recursive(input_numbers):
    print('true')
else:
    print('false')

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务