Reputation: 13
I'm trying to make poker game in Python. In the while fuction I want to move the used cards in a separate(used cards) list. The problem is sometimes when I print the hand I can get duplicates. Something is wrong with my sorting strategy and I don't know what. Can you help me?
import random
deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\
'AD', 'KD', 'QD', 'JD', '10D', '9D', '8D', '7D', '6D', '5D', '4D', '3D', '2D',\
'AC', 'KC', 'QC', 'JC', '10C', '9C', '8C', '7C', '6C', '5C', '4C', '3C', '2C',\
'AH', 'KH', 'QH', 'JH', '10H', '9H', '8H', '7H', '6H', '5H', '4H', '3H', '2H']
used = []
p1 = []
p2 = []
a = 0
while (a < 2):
drawn_card = random.choice(deck)
deck.append(drawn_card)
deck = [f for f in deck if f not in used]
p1.append(drawn_card)
a+=1
Upvotes: 1
Views: 94
Reputation: 19
you need to compare the random card with "p1" not with "deck":
import random
deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\
'AD', 'KD', 'QD', 'JD', '10D', '9D', '8D', '7D', '6D', '5D', '4D', '3D', '2D',\
'AC', 'KC', 'QC', 'JC', '10C', '9C', '8C', '7C', '6C', '5C', '4C', '3C', '2C',\
'AH', 'KH', 'QH', 'JH', '10H', '9H', '8H', '7H', '6H', '5H', '4H', '3H', '2H']
used = []
p1 = []
a = 0
while (a < 2):
drawn_card = random.choice(deck)
print(drawn_card)
if drawn_card not in p1:
p1.append(drawn_card)
a += 1
continue
print (p1)
Upvotes: 0
Reputation: 73394
Well the random choice is not guaranteed to be unique, thus when you do:
drawn_card = random.choice(deck)
..
p1.append(drawn_card)
you may end up having duplicates (that explains that you some time see duplicates and some not).
Check if drawn_card
is in the list first and if not, then append. That way you won't have duplicates. In code you could it like this:
if drawn_card not in p1:
p1.append(drawn_card)
Or, as Rory Daulton said:
If you are allowed, you could shuffle the entire deck, then remove consecutive items from that list.
Upvotes: 1