欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python 计算器 24 点游戏

最编程 2024-04-27 21:59:42
...

结果如下:

表达式结果

代码如下:

# -*- coding: utf-8 -*-
# @Time : 2019/11/10 11:45
# @Author : Administrator 
# @File : pailiezuhe.py
# @Software: PyCharm

# from itertools import combinations #4个里面不允许出现重复
# print(list(combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4)))
import itertools
from itertools import product
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#print(list(product(l, l)))
l1 = list(product(l, repeat=4))
#print(l1)
print(len(l1))
l2 = []
print(len(l2))
for i in l1:
    l2.append(list(i))
#print(l2)



def twentyfour(cards):
    '''史上最短计算24点代码'''
    for nums in itertools.permutations(cards):  # 四个数
        for ops in itertools.product('+-*/', repeat=3):  # 三个运算符(可重复!)
            # 构造三种中缀表达式 (bsd)
            bds1 = '({0}{4}{1}){5}({2}{6}{3})'.format(*nums, *ops)  # (a+b)*(c-d)
            bds2 = '(({0}{4}{1}){5}{2}){6}{3}'.format(*nums, *ops)  # (a+b)*c-d
            bds3 = '{0}{4}({1}{5}({2}{6}{3}))'.format(*nums, *ops)  # a/(b-(c/d))

            for bds in [bds1, bds2, bds3]:  # 遍历
                try:
                    if abs(eval(bds) - 24.0) < 1e-10:  # eval函数
                        return bds
                except ZeroDivisionError:  # 零除错误!
                    continue

    return 'Not found!'
for card in l2:
    print(twentyfour(card))

控制台所有结果如下:

G:\python_projectkotin\venv\Scripts\python.exe G:/python_projectkotin/python_matrix_gh/suanfa/pailiezuhe.py
10000
0

(1+1)*(3*4)
(1+3)*(1+5)
((1*1)+3)*6
((1*1)+7)*3
(1-1)+(3*8)
(1+1)*(3+9)
3*(10-(1+1))
Not found!
Not found!
(1+1)*(4*3)
((1+1)+4)*4
((1*1)+5)*4
(1-1)+(4*6)
(1*4)*(7-1)
(1+1)*(4+8)
(1-4)*(1-9)
((1+1)*10)+4
Not found!
Not found!
(1+5)*(1+3)
((1*1)+5)*4
(1+5)*(5-1)
((1*5)-1)*6
(1+1)*(5+7)
((5-1)-1)*8
Not found!
Not found!
Not found!
(1+1)*(6*2)
((1+1)+6)*3
(1-1)+(6*4)
(1*6)*(5-1)
(1+1)*(6+6)
Not found!
(6*8)/(1+1)
((1+1)*9)+6
Not found!
Not found!
(1+7)*(1+2)
((1*1)+7)*3
((1*7)-1)*4
(1+1)*(7+5)
...
.
.
...

8+(8/(5/10))
8*(8-(6-1))
(8+8)+(6+2)
8+(8*(6/3))
8+(8*(6-4))
8*(6-(8-5))



Process finished with exit code 0