-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsequenceprotocol.py
More file actions
50 lines (31 loc) · 1.15 KB
/
sequenceprotocol.py
File metadata and controls
50 lines (31 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import collections
from random import choice
from random import shuffle
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
# First of two methods needed for immutable sequence protocol
def __len__(self):
return len(self._cards)
# Second of two methods needed for immutable sequence protocol
def __getitem__(self, item):
return self._cards[item]
# Third method to convert immutable sequence protocol to mutable sequence protocol
def __setitem__(self, key, value):
self._cards[key] = value
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
deck = FrenchDeck()
for card in deck:
print(card)
for card in sorted(deck, key=spades_high):
print(card)
print(choice(deck))
shuffle(deck)
for card in deck:
print(card)