多次使用新结果调用函数

2024-04-20 01:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个扑克模拟,创建一定数量的5张牌扑克手,看看我需要玩多少次,直到我得到皇家同花顺。。。你知道吗

我编写了一个生成5张牌的函数,但当我多次运行该函数时,它将不起作用-->;我得到5*x张牌,而不是每5张牌有多只手

import random

d = []
h = []

def cards():

    l1 = ["Herz", "Karo", "Pik", "Kreuz"]
    l2 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    for i in range(10):
        d.append([])
    for k in range(10):
        d[k].append(l1[random.randint(0, (len(l1) - 1))])
        d[k].append(l2[random.randint(0, (len(l2) - 1))])
    for a in d:
        if a not in h:
            h.append(a)
            if len(h) == 5:
                break
        else:
            continue
    return h

for i in range(2):
    print(cards())

当我运行代码时,我得到以下结果:

[['Karo', 8], ['Herz', 5], ['Pik', 13], ['Herz', 12], ['Karo', 3]]

[['Karo', 8, 'Karo', 5], ['Herz', 5, 'Karo', 6], ['Pik', 13, 'Herz', 4], ['Herz', 12, 'Herz', 5], ['Karo', 3, 'Pik', 3], ['Karo', 8, 'Kreuz', 3], ['Karo', 9, 'Kreuz', 3], ['Pik', 13, 'Herz', 10], ['Pik', 6, 'Karo', 11], ['Karo', 2, 'Pik', 13], []]


Tags: 函数inl1forlenrangerandomcards
1条回答
网友
1楼 · 发布于 2024-04-20 01:36:36

您的代码当前有它一直附加到的全局列表。这几乎肯定不是你想要的。你知道吗

我建议创建一副牌,在没有替换的情况下对它们进行抽样,得到五张牌。你可以从一副52张牌中得到10张这样的牌。更好的方法可能是创建牌组并洗牌,一次挑选5张牌,直到它包含少于5张牌。你知道吗

在任何一种情况下,您都可以将每只手传递给一个函数,该函数将测试它是否是一个flush或您想要的任何东西。你知道吗

为此所需的所有工具(在使用numpy之前)都在^{}^{}模块中。你知道吗

首先创建一个全局组。没有必要多次这样做,因为这会让你毫无目的地慢下来。牌组不会改变,只有顺序会:

rank = [str(x) for x in range(2, 11)] + list('JQKA')
suit = list('♠♥♦♣')
deck = list(''.join(card) for card in itertools.product(rank, suit))

现在你可以使用这个牌组一次生成1到10手牌,中间没有重复牌。关键是洗牌要到位。您不必每次都重新生成甲板:

def make_hands(cards=5, hands=None):
    if hands is None:
        hands = len(deck) // cards
    if cards * hands > len(deck):
        raise ValueError('you ask for too much')
    if cards < 1 or hands < 1:
        raise ValueError('you ask for too little')
    random.shuffle(deck)
    result = [deck[cards * i:cards * i + cards] for i in range(hands)]

您可以使用此功能更改所需的每手牌数和每副牌的牌数。假设您还有一个函数来检查一只手是否是一个flush,这个函数名为isflush。你可以这样应用:

def how_many():
    shuffles = 0
    hands = 0
    while True:
        shuffles += 1
        cards = make_hands()
        for hand in cards:
            hands += 1
            if isflush(hand):
                return shuttles, hands

shuffles, hands = how_many()
print(f'It took {hands} hands with {shuffles} reshuffles to find a flush')

相关问题 更多 >