这本书还是月初的时候翻了翻,看了前十章左右就发现这本书写的比较烂,翻译地就更烂了,讲的内容其实没有抓住重点。
下面是看的时候记得几小段代码:
1 #首字母相同的男生女生
2 girls = ['alice', 'bernice', 'clarice']
3 boys = ['chris', 'arnold', 'bob']
4 lettergirls = {}
5 for girl in girls:
6 lettergirls.setdefault(girl[0], []).append(girl)
7 print([b+'+'+g for b in boys for g in lettergirls[b[0]]])
8
9 #斐波那契数列
10 def fibs(num):
11 result = [1, 2]
12 for i in range(num - 2):
13 result.append(result[-2] + result[-1])
14 return result
15 print(fibs(20))
16
17 #存储全名的字典
18 def init(data):
19 data['first'] = {}
20 data['middle'] = {}
21 data['last'] = {}
22 def lookup(data, label, name):
23 return data[label].get(name)
24 def store(data, full_name):
25 names = full_name.split()
26 if len(names) == 2:
27 names.insert(1, ' ')
28 labels = ('first', 'middle', 'last')
29 for label, name = zip(labels, names):
30 people = lookup(data, label, name)
31 if people:
32 people.append(full_name)
33 else:
34 data[label][name] = [full_name]
35
36 #递归经典:阶乘、幂、二分查找
37 def search(sequence, number, lower, upper):
38 if lower == upper:
39 assert number == sequence[upper]
40 return upper
41 else:
42 middle = (lower + upper) // 2
43 if number > sequence[middle]:
44 return search(sequence, number, middle + 1, upper)
45 else:
46 return search(sequence, number, lower, middle)
47
48 #模拟实现无穷算术序列
49 def checkIndex(key):
50 if not isinstance(key, (int, long)):
51 raise TypeError
52 if key < 0:
53 raise IndexError
54 class ArithmeticSequence:
55 def __init__(self, start = 0, step = 1):
56 self.start = start
57 self.step = step
58 self.changed = {}
59 def __getitem__(self, key):
60 checkIndex(key)
61 try:
62 return self.changed[key]
63 except KeyError:
64 return self.start + key * self.step
65 def __setitem__(self, key, value):
66 checkIndex(key)
67 self.changed[key] = value
1 #基本的序列与映射规则
2 def checkIndex(key):
3 if not isinstance(key, (int, long)):
4 raise TypeError
5 if key < 0:
6 raise IndexError
7 class ArithmeticSequence:
8 def __init__(self, start = 0, step = 1):
9 self.start = start
10 self.step = step
11 self.changed = {}
12 def __getitem__(self, key):
13 checkIndex(key)
14 try:
15 return self.changed[key]
16 except KeyError:
17 return self.start + key * self.step
18 def __setitem__(self, key, value):
19 checkIndex(key)
20 self.changed[key] = value
21 #带有访问计数的列表
22 class CounterList(list):
23 def __init__(self, *agrs):
24 super(CounterList, self).__init__(*args)
25 self.counter = 0
26 def __getitem__(self, index):
27 self.counter += 1
28 return super(CounterList, self).__getitem__(index)