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])

Original: https://blog.csdn.net/qq_42158153/article/details/125325776
Author: 水月清辉
Title: python之24点牌游戏

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/780275/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球