杨辉三角定义如下:
1
1 1
1 2 1
1 3 3 1
把每一行看作一个list,试写一个 生成器,不断输出下一行的list,要求输出前10行。
>>> def Yh(n):
L=[1]
for _ in range(n-1):
L=[sum(_) for _ in zip([0]+L,L+[0])]
return L
>>> def yh(n):
for i in range(1,n+1):
yield Yh(i)
>>> t = yh(10)
>>> 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]
>>> next(t)
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]