需要帮助我的shuffle卡计划

时间:2011-05-07 06:06:45

标签: python

我正在做一个洗牌计划。最后我用for loop打印出10张随机卡,但我不知道它有什么问题。

最后deal_card(card),为什么我放card因为我的h / w这样说,但如果你有其他答案,我会很高兴听你说的。

这是我的计划:

import random

def define_cards():
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    cards = []
    for suit in range(4):
        for rank in range(13):
            card_string = rank_string[rank] + " of " + suit_string[suit]
            cards.append(card_string)
        return cards

def create_deck(deck):
    for i in range(52):
        deck.append(i)
        return

def shuffle_deck(deck):
    random.shuffle(deck)
    return

def deal_card(deck):
    return deck.pop(0)

deck=[]

create_deck(deck)
shuffle_deck(deck)
print "The first 10 cards are:"
for i in range(10):             # I don't know why won't work
    deal_card(card)
    print define_cards()

打印出来的样子:

The first 10 cards are:
queen of hearts
ten of diamonds
...

3 个答案:

答案 0 :(得分:6)

由于您的define_cards已经生成了卡片名称列表,因此您应该使用它来生成卡片而不是create_deck。然后在for循环中,只需处理一张卡并打印出来。

deck = define_cards()
shuffle_deck(deck)
print "The first 10 cards are:"
for i in range(10):
    card = deal_card(deck)
    print card

这样做可以使程序从卡座顶部打印十张卡片。但是,define_cards仍然有一点bug。你能发现它吗?提示:return的定位。

答案 1 :(得分:3)

一半的代码是多余的:

>>> import random
>>> deck = range(1,52)
>>> random.shuffle(deck)
>>> deck
[4, 38, 40, 18, 35, 44, 50, 22, 49, 26, 8, 45, 14, 20, 25, 34, 37, 51, 42, 29, 24, 28, 27, 30, 7, 47, 23, 3, 10, 2, 9, 39, 6, 16, 12, 17, 11, 41, 33, 48, 5, 1, 36, 21, 13, 32, 43, 19, 15, 31, 46]

答案 2 :(得分:1)

您可能想要考虑创建一个类卡和一个类Deck来维护一副牌。这将为您提供更清晰的代码。