1. 程式人生 > >【Python】用生成器generator簡單實現楊輝三角

【Python】用生成器generator簡單實現楊輝三角

楊輝三角,又稱賈憲三角形,帕斯卡三角形,是二項式係數在三角形中的一種幾何排列。

def triangles():
L=[1]
while(True):
yield L
L=[1]+[x+y for x,y in zip(L[:-1],L[1:])]+[1]
n = 0
max=int(input('請輸入楊輝三角的行數:'))
for t in triangles():
print(t)
n = n + 1
if n > max:
break

執行結果