流畅的python第一章 出错_流畅的python(1)

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值