python学习笔记(九)杨辉三角的实现

杨辉三角代码的艺术
杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,写一个generator,不断输出下一行的list

方案一:普通代码

使用前一行pre,导出当前行cur

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def triangles(max):
triangle = [[1]]
n = 0
while n<max:
pre = triangle[n]
cur = []
yield pre
length = len(pre) + 1
cur.append(1)
if length > 2:
for m in range(1,length-1):
cur.append(pre[m-1]+pre[m])
cur.append(1)
triangle.append(cur)
n = n+1
return 'Done'

方案二:使用zip内置函数

代码的艺术:

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
>>> def triangle2():
... L = [1]
... while True:
... yield L
... L = [x+y for x,y in zip([0]+L, L+[0])]
...
>>> t = triangle2()
>>> next(t)
[1]
>>> next(t)
[1, 1]
>>> next(t)
[1, 2, 1]
>>> next(t)
[1, 3, 3, 1]
>>> next(t)
[1, 4, 6, 4, 1]
>>> next(t)
[1, 5, 10, 10, 5, 1]
>>> next(t)
[1, 6, 15, 20, 15, 6, 1]
>>> next(t)
[1, 7, 21, 35, 35, 21, 7, 1]
>>> next(t)
[1, 8, 28, 56, 70, 56, 28, 8, 1]

仅一行关键性代码L = [x+y for x,y in zip([0]+L, L+[0])]

zip()函数

原型为:zip([iterable, ...])
参数Iterable为可迭代对象,并且可以返回多个参数。该函数返回一个以元组为元素的列表,其中第i个元组包含每个参数序列的第i个元素。返回的列表长度被截断为最短参数序列的长度。只有一个序列参数时,他返回一个1元组的列表,没有参数时,它返回一个空列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> a = [1,2,3]
>>> b = (5,6,7)
>>> c = 'abc'
>>> d = 'f'

>>> for n in (zip(a,b)):
... print(n)
...
(1, 5)
(2, 6)
(3, 7)

>>> for n in (zip(a,c)):
... print(n)
...
(1, 'a')
(2, 'b')
(3, 'c')

>>> for n in (zip(a,d)):
... print(n)
...
(1, 'f')