In [1]:
from math import hypot
In [2]:
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return("Vector({}, {})".format(self.x, self.y))
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
In [3]:
v1 = Vector(2 ,4)
v2 = Vector(2, 1)
v1 + v2
Out[3]:
In [4]:
v = Vector(3, 4)
abs(v)
Out[4]:
In [5]:
v * 3
Out[5]:
In [6]:
abs(v * 3)
Out[6]:
In [7]:
import collections
In [8]:
Card = collections.namedtuple('Card', ['rank', 'suit'])
In [9]:
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]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
In [10]:
beer_card = Card('Y', 'diamonds')
In [11]:
beer_card
Out[11]:
In [12]:
deck = FrenchDeck()
In [13]:
len(deck)
Out[13]:
In [14]:
deck[0]
Out[14]:
In [15]:
deck[-1]
Out[15]:
In [16]:
from random import choice
choice(deck)
Out[16]:
In [17]:
choice(deck)
Out[17]:
In [18]:
choice(deck)
Out[18]:
In [19]:
deck[:3]
Out[19]:
In [20]:
deck[12::13]
Out[20]:
In [21]:
deck[8::13]
Out[21]:
In [22]:
for card in deck:
print(card)
In [23]:
Card('Q', 'hearts') in deck
Out[23]:
In [24]:
Card('7', 'beasts') in deck
Out[24]:
In [25]:
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
In [26]:
def spades_high(card):
# rank of the rank: {2 = 0 .. A = 12}
rank_value = FrenchDeck.ranks.index(card.rank)
# sort by rank, then by suit
return rank_value * len(suit_values) + suit_values[card.suit]
In [27]:
for card in sorted(deck, key=spades_high):
print(card)
In [ ]:
In [ ]: