杨辉三角杨辉 定义如下:
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 M=L[:]#复制一个list,这样才不会影响到原有的list。不然results里的每个列表的末尾会为0. M.append(0) L = [M[i-1]+M[i] for i in range(len(M))] n =0 results = [] for t in triangles(): print(t) results.append(t) print(results) n = n +1 if n == 10: break