栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python之24点牌游戏

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python之24点牌游戏

# -*- coding: UTF-8 -*-
from itertools import combinations
from itertools import permutations

str1 = "1 2 J A"
card = str1.split(" ")
re_ref = ['J', 'Q', 'K', 'A']
i_ref = [11, 12, 13, 1]

# 运算符
def getYS():
    result = []
    list1 = ['+', '-', '*', '/'] * 3
    for p in combinations(list1, 3):
        result.append(p)
    return list(set(result))
# print(len(getYS()))

# 获取牌顺序
def getCard(card):
    result = []
    for p in permutations(card, 4):
        list1 = []
        list1.append(p[0])
        list1.append(p[1])
        list1.append(p[2])
        list1.append(p[3])
        result.append(list1)
    return result

# print(len(getCard(card)))

# 获取表达式
def getExpress1(card):
    result = []
    for i in getYS():
        tmp = card[:]
        tmp.insert(1, i[0])
        tmp.insert(3, i[1])
        tmp.insert(5, i[2])
        result.append(tmp)
    return result

# print(getExpress(card))

#添加括号
def getExpress2(list1):
    #只有一个*或者/
    if list1.count("*") + list1.count("/") == 1:
        if list1[3] == "*" or list1[3] == "/":
            list1.insert(0, "(")
            list1.insert(4, ")")
        elif list1[5] == "*" or list1[5] == "/":
            list1.insert(0, "(")
            list1.insert(6, ")")
    #有两个*或者/
    elif list1.count("*") + list1.count("/") == 2:
        if (list1[1] == "*" or list1[1] == "/") and (list1[5] == "*" or list1[5] == "/"):
            list1.insert(0, "(")
            list1.insert(6, ")")
        elif (list1[1] == "*" or list1[1] == "/") and (list1[5] == "*" or list1[5] == "/"):
            list1.insert(0, "(")
            list1.insert(4, ")")
    return list1

#生成字符串表达式
def getExpress3(card, res_result):
    result = getExpress1(card)
    for i in result:
        list1 = getExpress2(i)
        str1 = ''
        for j in list1:
            str1 = str1 + str(j)
        if eval(str1) == 24:
            str2 = str1.replace('.', '').replace('0', '').replace('(', '').replace(')', '')
            res_result.append(str2.replace('11', 'J').replace('12', 'Q').replace('13', 'K').replace('1', 'A'))

res_result = []
if "joker" in card or "JOKER" in card:
    print('ERROR')
else:
    for i in card:
        if i in re_ref:
            card[card.index(i)] = float(i_ref[re_ref.index(i)])
        else:
            card[card.index(i)] = float(i)
    print(card)
    for j in getCard(card):
        getExpress3(j, res_result)
    if len(res_result) == 0:
        print('NONE')
    else:
        #print(list(set(res_result)))
        print(list(set(res_result))[0])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号