现在的小学生的课后作业是算24点,看了一下题目,发现都挺难的,只能用加减乘除,算出24点。

都开始使用分数(小数)来计算24点了,发现心算不容易,于是从网上找找,用Python写了一个程序来算。

把下面的代码保存到24.py文件

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("Found %d solutions." %len(res))
    for i, s in enumerate(res):
        print("%d: %s = 24" %(i+1, s))
    print("\n")



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

 在命令行中执行python 24.py,就可以看到结果了。