patternpythonMinor
Poker deck class /w generator function and list comprehensions
Viewed 0 times
pokerdeckfunctiongeneratorcomprehensionsandlistclass
Problem
There are multiple aspects in the code I do not really like.
[card for card in ...] looks really lame, also [x.pop() for i in range(y)]. I'm looking forward for any recommendation.from random import shuffle
class Deck(object):
suits = range(4)
ranks = range(13)
@classmethod
def generator(cls, suits, ranks):
for suit in suits:
for rank in ranks:
yield({'suit': suit, 'rank': rank})
def __init__(self):
self.cards = [card for card in Deck.generator(Deck.suits, Deck.ranks)]
shuffle(self.cards)
def deal(self, amount):
return [self.cards.pop() for i in range(amount)]
print Deck().deal(5)Solution
[card for card in Deck.generator(…)] could be written as list(Deck.generator(…)).Better yet, use
itertools.product():self.cards = [
{'suit': suit, 'rank': rank}
for suit, rank in itertools.product(xrange(4), xrange(13))
]In Python 2, you should be using
xrange() rather than range().It's probably worth defining a
Card class. At some point, you'll want to have suits that are named rather than numbered, and ranks A, J, Q, K rather than 0..12.To deal multiple cards, you can slice the list instead of popping one card at a time:
def deal(self, n):
hand = self.cards[-1 : -n-1 : -1]
self.cards = self.cards[: -n]
return handCode Snippets
self.cards = [
{'suit': suit, 'rank': rank}
for suit, rank in itertools.product(xrange(4), xrange(13))
]def deal(self, n):
hand = self.cards[-1 : -n-1 : -1]
self.cards = self.cards[: -n]
return handContext
StackExchange Code Review Q#99254, answer score: 2
Revisions (0)
No revisions yet.