杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
正确实践:
def triangles
L=[1]
while True:
yield L #打印出该list
L=[L[x]+L[x+1] for x in range(len(L)-1)] #计算下一行中间的值
L.insert(0,1) #在开头插入1
L.append(1) #在结尾添加1
if len(L)>10: #仅输出10行
break
正确实践:
L = [1]
while True:
yield L
L = [1] + [x + L[i+1] for i,x in enumerate(L[:-1]) ] + [1]
错误实践:
def triangles():
L = [1]
while True:
yield L
L = [1] + [L[i] + L[i+1] for i in enumerate(L[:-1])] + [1]
L = [1] + [L[i] + L[i+1] for i in enumerate(L[:-1])] + [1]
TypeError: list indices must be integers or slices, not tuple