【python算法】24点()


def solution(numbers):
    res = set()

    def point24(numbers):
        if len(numbers) == 1:
            if abs(eval(numbers[0]) - 24) < 1e-10:
                res.add(numbers[0])
        else:
            for i in range(len(numbers)):
                for j in range(i + 1, len(numbers)):
                    # 剩下的数字
                    rest_numbers = [x for p, x in enumerate(numbers) if p != i and p != j]
                    for op in "+-*/":
                        if eval(str(numbers[j])) != 0:
                            point24(["(" + str(numbers[i]) + op + str(numbers[j]) + ")"] + rest_numbers)
                        if op == "-" or (op == "/" and eval(str(numbers[i])) != 0):  # 要考虑相反的情况
                            point24(["(" + str(numbers[j]) + op + str(numbers[i]) + ")"] + rest_numbers)

    point24(numbers)
    print(res)


solution([5, 5, 5, 1])
solution([1, 3, 4, 6])
solution([10, 10, 4, 4])
solution([10, 5, 2, 1])

参考:https://zhuanlan.zhihu.com/p/37608401

————————

def solution(numbers):
    res = set()

    def point24(numbers):
        if len(numbers) == 1:
            if abs(eval(numbers[0]) - 24) < 1e-10:
                res.add(numbers[0])
        else:
            for i in range(len(numbers)):
                for j in range(i + 1, len(numbers)):
                    # 剩下的数字
                    rest_numbers = [x for p, x in enumerate(numbers) if p != i and p != j]
                    for op in "+-*/":
                        if eval(str(numbers[j])) != 0:
                            point24(["(" + str(numbers[i]) + op + str(numbers[j]) + ")"] + rest_numbers)
                        if op == "-" or (op == "/" and eval(str(numbers[i])) != 0):  # 要考虑相反的情况
                            point24(["(" + str(numbers[j]) + op + str(numbers[i]) + ")"] + rest_numbers)

    point24(numbers)
    print(res)


solution([5, 5, 5, 1])
solution([1, 3, 4, 6])
solution([10, 10, 4, 4])
solution([10, 5, 2, 1])

参考:https://zhuanlan.zhihu.com/p/37608401