Home > database >  python generator object for card dealer
python generator object for card dealer

Time:12-12

My question is to create a function which yields a type of card at one time. e.g. card_dealer() which only outputs any one combination e.g.10S.

My attempt is

def card_dealer():
    rank = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
    suit = ['S','C','H','D']
    list3=[]
    num=0
    for i in rank[num]:
        for j in suit[num]:
            list3.append(f'{i}{j}')
            num =1
            yield list3

next(card_dealer())

However this only outputs the same one combination when I keep running next(card_dealer()):

['2S']

How would I make it so that when I run next(card_dealer()) I would get the next combination e.g. 2C. I've thought about using import random to randomise rather than output a combination in order, but thats for another day! I've tried different combinations of this code e.g. moving the yield in different indentations but it doesn't give the specific result I want.

CodePudding user response:

I think this is how I would prefer to write this function. card_dealer's job is to deal cards, not make the deck after all.

from random import shuffle


def card_dealer(deck):
    for card in deck:
        yield card

    yield None


ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
suits = ['S','C','H','D']

deck = [rank   suit for suit in suits for rank in ranks]
shuffle(deck)

for card in card_dealer(deck):
    print(card or "Dealer is out of cards")

CodePudding user response:

That isn't how for loops work in Python. I'd recommend checking out this article for a good, thorough explanation, but the short version is that you don't need those indexes. Your current code:

for i in rank[num]:

only evaluates rank[num] at the beginning. Since num is 0, you're only ever iterating through the string '2', not the list that it's part of. Here's something closer to what you want:

def card_dealer():
    ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
    suits = ['S','C','H','D']
    for rank in ranks:
        for suit in suits:
            yield f'{rank}{suit}'

for card in card_dealer():
    print(card)

However, this will still deal them in order. For randomization, you could use random.shuffle and something like this. (This also uses a list comprehension and, as suggested by chepner, the yield from syntax. Each could be a standard for loop instead.)

import random

def card_dealer():
    ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
    suits = ['S','C','H','D']
    cards = [f'{rank}{suit}' for rank in ranks for suit in suits]
    random.shuffle(cards)
    yield from cards

for card in card_dealer():
    print(card)
  • Related