上代码:
# 杨辉三角
def triangles():
L = [1]
while True:
yield L
L1 = []
L.insert(0, 0)
L.insert(len(L), 0)
#相邻数字相加
for x in range(len(L)-1):
L1.append(L[x]+L[x+1])
L = L1
return 'done'
results = []
generator1 = triangles()
for i in range(10):
results.append(next(generator1))
print(results)
最后的输出结果不符合预期,如下,下面一篇文章(https://www.jianshu.com/p/b55f90399182)解释原因。
预计输出结果:
[[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]]
实际输出结果:
[[0, 1, 0], [0, 1, 1, 0], [0, 1, 2, 1, 0], [0, 1, 3, 3, 1, 0], [0, 1, 4, 6, 4, 1, 0], [0, 1, 5, 10, 10, 5, 1, 0], [0, 1, 6, 15, 20, 15, 6, 1, 0], [0, 1, 7, 21, 35, 35, 21, 7, 1, 0], [0, 1, 8, 28, 56, 70, 56, 28, 8, 1, 0], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]
每一个next(generator1)里前后是没有0的,但是append到results之后下一次输出就有了
JackKun的简书
网友评论