杨辉三角定义如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
代码来自https://baike.baidu.com/item/杨辉三角#4_10
第一个方法:
>>> def triangles():
... L=[1]
... while True:
... yield L
... L = [sum(i) for i in zip([0]+L,L+[0])]
...
>>> n = 0
>>> results=[]
>>> for t in triangles():
... print(t)
... results.append(t)
... n= n+1
... if n==10:
... break
...
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
其中,zip函数的原型为:zip([iterable, …]) 参数iterable为可迭代的对象,并且可以有多个参数。该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度为最短的参数序列的长度。
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [8,9,10,11,12]
>>> zz = zip(a,b,c)
>>> print(zz)
<zip object at 0x10340ac88>
>>> next(zz)
(1, 4, 8)
>>> next(zz)
(2, 5, 9)
>>> next(zz)
(3, 6, 10)
>>> next(zz)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
该方式用到了列表生成式,理解起来较困难,下面是另一种方式:
def triangles():
ret = [1]
while True:
yield ret
for i in range(1, len(ret)):
ret[i] = pre[i] + pre[i - 1]
ret.append(1)
pre = ret[:]
另一个不用生成器的版本:
1 2 3 4 5 |
|
在评论区看到了一个用生成器的方式:
def triangle():
L=[1]
while True:
yield L
G=[0]+L+[0]
L=[G[i]+G[i+1] for i in range(len(G)-1)]
return ('done')
# 期待输出:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
n = 0
results = []
for t in triangles():
print(t)
results.append(t)
n = n + 1
if n == 10:
break
if results == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
print('测试通过!')
else:
print('测试失败!')