1-1
import collections
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]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
1-2
from math import hypot
class Vector:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __repr__(self):
return 'Vector(%r,%r)'%(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)
2-17
import bisect
import sys
hay = [1,4,5,6,8,12,15,20,21,23,23,26,29,30]
needs = [0,1,2,5,8,10,22,23,29,30,31]
row = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for need in reversed(needs):
pos = bisect_fn(hay,need)
offset = pos * ' |'
print (row.format(need,pos,offset))
if __name__ == '__main__':
if sys.argv[-1]=='left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('demo:',bisect_fn.__name__)
print('hay->',' '.join('%2d' %n for n in hay))
demo(bisect_fn)
2-18
import bisect
def grade(score,breakpoints=[60,70,80,90],grade='FDCBA'):
i = bisect.bisect(breakpoints,score)
return grade[i]
print ([grade(score) for score in [33,99,77,70,89,90,100]])
2-19
import bisect
import random
size = 7
random.seed(1729)
my_list = []
for i in range(size):
new = random.randrange(size*2)
bisect.insort(my_list,new)
print('%2d->' %new,my_list)