用python算24点及原理详解

1 描述

给出4个正整数,使用加、减、乘、除4种运算以及括号把4个数连接起来得到一个结果等于24的表达式。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

注:这里加、减、乘、除以及括号的运算结果和运算优先级跟平常定义一致。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬

例如,对于5,5,5,1,可知 5× (5-1/5) = 24。又如,对于 1,1,4,2 无论如何都不能得到24

1.1 输入格式

在代码中的输入部分输入4个正整数。

1.2 输出格式

对于每一组测试数据,如果可以得到24,输出"YES"其算法;否则输出“NO”。

2 大致思路

将四个数字进行全排列,在他们之间添加运算符号,最后将数字和操作符进行拼接运算。

运算符我们需要进行排列组合,因为只有四个数字,所以只需要三个运算符,而且算法符可能会重复,比如三个都是+。

再遍历四个数字的全排列,对每一组数字而言,遍历所有组合的操作符。最后将数字和操作符进行拼接运算,就可以得到最终结果了。

3 知识点补充

1、首先我们对所有数字进行去全排列,这里我们使用 itertools.permutations 来帮助我们完成。

iertools.permutations 用法演示

import itertools

a = int(input("请输入第1个数字:"))
b = int(input("请输入第2个数字:"))
c = int(input("请输入第3个数字:"))
d = int(input("请输入第4个数字:"))

my_list = [a, b, c, d]
result = [c for c in itertools.permutations(my_list, 4)]

for i, r in enumerate(result):
    if i % 4 == 0:
        print()
    print(r, end="\t")
print("\n\n长度为:", len(result))

运行结果:

请输入第1个数字:1
请输入第2个数字:2
请输入第3个数字:3
请输入第4个数字:4

(1, 2, 3, 4)	(1, 2, 4, 3)	(1, 3, 2, 4)	(1, 3, 4, 2)	
(1, 4, 2, 3)	(1, 4, 3, 2)	(2, 1, 3, 4)	(2, 1, 4, 3)	
(2, 3, 1, 4)	(2, 3, 4, 1)	(2, 4, 1, 3)	(2, 4, 3, 1)	
(3, 1, 2, 4)	(3, 1, 4, 2)	(3, 2, 1, 4)	(3, 2, 4, 1)	
(3, 4, 1, 2)	(3, 4, 2, 1)	(4, 1, 2, 3)	(4, 1, 3, 2)	
(4, 2, 1, 3)	(4, 2, 3, 1)	(4, 3, 1, 2)	(4, 3, 2, 1)	

长度为: 24

4 具体代码

from itertools import permutations

a = int(input("请输入第1个数字:"))
b = int(input("请输入第2个数字:"))
c = int(input("请输入第3个数字:"))
d = int(input("请输入第4个数字:"))
my_list = [a, b, c, d]
# 对4个整数随机排列的列表
result = [c for c in permutations(my_list, 4)]

symbols = ["+", "-", "*", "/"]

list2 = []  # 算出24的排列组合的列表

flag = False

for one, two, three, four in result:
    for s1 in symbols:
        for s2 in symbols:
            for s3 in symbols:
                if s1 + s2 + s3 == "+++" or s1 + s2 + s3 == "***":
                    express = ["{0}{1}{2}{3}{4}{5}{6}".format(one, s1, two, s2, three, s3, four)]  # 全加或者乘时,括号已经没有意义。
                else:
                    express = ["(({0}{1}{2}){3}{4}){5}{6}".format(one, s1, two, s2, three, s3, four),
                               "({0}{1}{2}){3}({4}{5}{6})".format(one, s1, two, s2, three, s3, four),
                               "(({0}{1}({2}{3}{4})){5}{6})".format(one, s1, two, s2, three, s3, four),
                               "{0}{1}(({2}{3}{4}){5}{6})".format(one, s1, two, s2, three, s3, four),
                               "{0}{1}({2}{3}({4}{5}{6}))".format(one, s1, two, s2, three, s3, four)]

                for e in express:
                    try:
                        if eval(e) == 24:
                            list2.append(e)
                            flag = True
                    except ZeroDivisionError:
                        pass

list3 = set(list2)  # 去除重复项

for c in list3:
    print("YES:", c)

if not flag:
    print("NO!")

猜你喜欢

转载自blog.csdn.net/apollo_miracle/article/details/105611278