Python3 24点游戏 含括号计算扑克 随机抽取 详解

题目:
24点游戏是在一副牌中抽去大小王剩下52张,随机抽取4张牌,用加、减、乘、除(可加括号)把牌面上的数算成24,则赢得该局。

除了数字2,3,4,5,6,7,8,9,10外A=1,J=11,Q=12,K=13。代表每个数的牌都有4张。

代码:

# !/usr/bin/python
# coding:utf8

import itertools
import random

#随机抽取4张牌
fourNum = [random.randint(1, 13) for i in range(4)]    # 随机4个数

print("你抽到的4张牌为:")
print(fourNum)

#所有4个数字的无重复的排列
array = []
[array.append(nl) for nl in list(itertools.permutations(fourNum)) if nl not in array]  

 #运算符号
operation = ['+','-','*','/']

#3个运算符号的排列
operation_array = list(itertools.product(operation,repeat=3))  # 操作符重复组合3位
 
#组合得到式子
method = [[str(nl[0])+'*1.0']+[ol[0]]+[str(nl[1])+'*1.0']+[ol[1]]+[str(nl[2])+'*1.0']+[ol[2]]+[str(nl[3])+'*1.0'] for nl in array for ol in operation_array]   # 拼凑4个数和3个操作符


#组合得到带括号的式子
together = []
for come in method:
    if ('*' not in come and  '/' not in come) or ('*' in come and  '/' in come):
        together.append(''.join(come))
    else:
        together.append(''.join(['(']+come[:3]+[')']+come[3:]))
        together.append(''.join(['(']+come[:5]+[')']+come[5:]))
        together.append(''.join(come[:2]+['(']+come[2:5]+[')']+come[5:]))
        together.append(''.join(come[:2]+['(']+come[2:7]+[')']))
        together.append(''.join(come[:4]+['(']+come[4:7]+[')']))
        together.append(''.join(['(']+come[:3]+[')']+come[3:4]+['(']+come[4:7]+[')']))

print("结果:")
i = 0
for maybe in together:
    try:
        if eval(maybe) == 24:  #判断结果
            print (maybe.replace('*1.0','')+'=24' )  
        else:
            i += 1
    except ZeroDivisionError as e:
    #除0错误
        i += 1
        continue
 #没有答案
if i == len(together):
    print ('你的牌不能组成24点!')

运行结果:
在这里插入图片描述在这里插入图片描述在这里插入图片描述

发布了9 篇原创文章 · 获赞 13 · 访问量 279

猜你喜欢

转载自blog.csdn.net/qnsEmma/article/details/104805309