#杨辉三角 python
#目标 输出如下
# [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]
#程序如下:
def triangles():
l = [1] #定义L为一个只包含一个元素的列表
while True:
yield l #定义为生成器函数
l = [1] + [l[i]+l[i+1] for i in range(len(l)-1)] + [1]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
”’
运行流程和思路如下:
输出:
第一行:L = [1]
第二行思路:
len(L) = 1
range(0) = []
“>>> for i in range(0):
print(i)
输出为空 ”
所以[l[i]+l[i+1] for i in range(len(l)-1)] ==[] 空
所以第二行:L = [1] + [1]
第二行结果: L = [1, 1]
第三行思路:
len(L)= 2 “因为 L=[1,1]”
range(1)=[0]
“因为 >>> for i in range(1):
print(i)
>>>0 ”
所以第三行:L = [1] + [L[0] + L[1] ] + [1]
[L[0] + L[1]] “等于取刚才 L[1,1] 的0位和1位”
L = [1] + [L[0] + L[1] ] + [1]
[L[0] + L[1] =2
第三行结果:L = [1, 2, 1]
第四行思路:
len(L) = 3 ‘因为此时 L=[1,2,1] 长度是3’
range(2)=[0,1]
第四行:L = [1] + [ L[0] + L[1], L[1] + L[2] ] + [1]
L[0] + L[1] == 3 “因为此时L=[1,2,1],取0位和1位的1和2 加起来就是3”
L[1] + L[2] ==3
L = [1] + [ 2 + 1, 1 + 2 ]+ [1]
L = [1] + [3] + [3] + [1]
L = [1, 3, 3, 1]
”’
公众号:来自世界的美意