|
1 | 1 | import collections
|
| 2 | +from pprintpp import pprint as pprint |
| 3 | + |
| 4 | +Card = collections.namedtuple("Card", ["rank", "suit"]) |
2 | 5 |
|
3 |
| -Card = collections.namedtuple('Card', ['rank', 'suit']) |
4 | 6 |
|
5 | 7 | class FrenchDeck:
|
6 |
| - ranks = [str(n) for n in range(2, 11)] + list('JQKA') |
7 |
| - suits = 'spades diamonds clubs hearts'.split() |
| 8 | + ranks = [str(n) for n in range(2, 11)] + list("JQKA") |
| 9 | + # => ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] |
| 10 | + |
| 11 | + suits = "spades diamonds clubs hearts".split() |
| 12 | + # => ['spades', 'diamonds', 'clubs', 'hearts'] |
8 | 13 |
|
9 | 14 | def __init__(self):
|
10 |
| - self._cards = [Card(rank, suit) for suit in self.suits |
11 |
| - for rank in self.ranks] |
| 15 | + self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] |
| 16 | + # => [Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), ...] |
12 | 17 |
|
13 | 18 | def __len__(self):
|
14 | 19 | return len(self._cards)
|
15 | 20 |
|
16 | 21 | def __getitem__(self, position):
|
17 | 22 | return self._cards[position]
|
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +if __name__ == "__main__": |
| 27 | + beer_card = Card("7", "diamonds") |
| 28 | + pprint(beer_card) # => Card(rank='7', suit='diamonds') |
| 29 | + print() |
| 30 | + |
| 31 | + deck = FrenchDeck() |
| 32 | + |
| 33 | + pprint(len(deck)) # => 52 |
| 34 | + print() |
| 35 | + |
| 36 | + pprint(deck[0]) # => Card(rank='2', suit='spades') |
| 37 | + print() |
| 38 | + |
| 39 | + pprint(deck[-1]) # => Card(rank='A', suit='hearts') |
| 40 | + print() |
| 41 | + |
| 42 | + pprint(deck[:3]) # => [Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')] |
| 43 | + print() |
| 44 | + |
| 45 | + pprint(deck[12::13]) # => [Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')] |
| 46 | + # note that the 12::13 is a slice, and it means start at 12, and take every 13th card |
| 47 | + print() |
| 48 | + |
| 49 | + # for card in deck: |
| 50 | + # print(card) |
0 commit comments