Reputation: 73
I am creating a black jack inspired game and i generate the deck and hand using the following code:
suits = 'SCHD'
values = '23456789TJQKA'
deck = tuple(''.join(card) for card in itertools.product(values, suits))
dealershand = random.sample(deck, 1)
yourhand = random.sample(deck, 2)
The problem with this is that there is a small chance that the same card is pulled in the 'dealershand' and 'yourhand' I would like to check if the card already exists, and if it does, to generate another card. Something like this:
while yourhand is in dealershand:
yourhand=random.sample(deck,2)
Upvotes: 1
Views: 111
Reputation: 1430
You can use random.shuffle(deck)
to shuffle the deck (which needs to be a list
rather than a tuple
) and then you can use deck.pop()
to draw one card at the time.
Upvotes: 10
Reputation: 120
there is a way to make it safely:
from itertools import product
from random import sample
suits = 'SCHD'
values = '23456789TJQKA'
deck = tuple(''.join(card) for card in product(values, suits))
dealershand = sample(deck, 1)
yourhand = sample(tuple([x for x in deck if x not in dealershand]), 2)
Upvotes: 0