开发者

Need help with my shuffle card program

开发者 https://www.devze.com 2023-03-04 13:04 出处:网络
I\'m doing a shuffle cards program.At the end i\'m using for loop to print out 10 random cards, but i don\'t know what wrong with it.

I'm doing a shuffle cards program.At the end i'm using for loop to print out 10 random cards, but i don't know what wrong with it.

On the end deal_card(card), why i put card because my h/w say so, but if you had other answer i'll be good to listen what you say.

This is my program:

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

Print out chould look like:

The first 10 cards开发者_StackOverflow社区 are:
queen of hearts
ten of diamonds
...


Since your define_cards already produces a list of card names, you should use that to generate the deck instead of create_deck. Then in the for loop just deal a card and print it.

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

Just doing this makes the program print ten cards from the top of the deck. However, define_cards still has a little bug. Can you spot it? Hint: positioning of return.


Half of the code is superfluous:

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


You might want to think about creating a class Card and an class Deck to maintain a deck of cards. This will give you clearer code.

0

精彩评论

暂无评论...
验证码 换一张
取 消