廖雪峰Python - 楊輝三角練習題
阿新 • • 發佈:2019-01-06
練習
楊輝三角定義如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一個list,試寫一個generator,不斷輸出下一行的list:
思路:
- 第n行有n個數;
- 把紅色數字部分看成整體,只需先計算這一部分,再在首尾添上‘1’即可;
- 由第n行決定第n-1行中紅色數字的值。
# -*- coding: utf-8 -*- # 期待輸出: # [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(): # 此處為我的答案 tri = [1] while True: yield tri maxIndex_m = len(tri) - 1 me = [] i = 0 while i < maxIndex_m: me.append(tri[i] + tri[i+1]) i += 1 tri = [1] + me + [1] n = 0 results = [] for t in triangles(): print(t) results.append(t) n = n + 1 if n == 10: break if results == [ [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] ]: print('測試通過!') else: print('測試失敗!')