杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
# -*- coding: utf-8 -*-
def triangles(max):
n = 0
L = [1]
while n < max: #设置生成器
yield L
L = [L[i] + L[i + 1 ] for i in range(len(L) - 1 ) ]
L.insert(0, 1)
L.append(1)
n = n + 1
print(L)
廖雪峰的网站上有一个oj系统,如果自主写一个杨辉三角并且打印的话,应该是这样的:
def Traingle(x):
Traingle_list = []
if x == 1:
Traingle_list = [1]
elif x == 2:
Traingle_list = [1,1]
else:
Traingle_list_temp = Traingle(x-1)
Traingle_list = [1,1]
temp = 1
while temp < x-1:
Traingle_list.insert(temp,Traingle_list_temp[temp]+Traingle_list_temp[temp-1])
temp = temp + 1
return Traingle_list
def PrintTraingle(x):
i = 0
while i < x:
print(Traingle(i+1))
i = i + 1