杨辉三角(python)
def triangles(num):
seeList = []
list = [1]
i=1
while i <= num:
if i==1:
yield(list)
if i==2:
list.append(1)
seeList = list[:]
yield(list)
if i>2:
index = 1
while index <=i-2:
list[index] = seeList[index-1] + seeList[index]
index = index + 1
list.append(1)
seeList = list[:]
yield(seeList)
i = i + 1
return 'done'
for t in triangles(10):
print(t)
结果
>>> for i in triangles(5):
print(i)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]