楊輝三角楊輝 定義以下:python
1 / \ 1 1 / \ / \ 1 2 1 / \ / \ / \ 1 3 3 1 / \ / \ / \ / \ 1 4 6 4 1 / \ / \ / \ / \ / \ 1 5 10 10 5 1
把每一行看作一個list,試寫一個generator,不斷輸出下一行的list:app
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