杨辉三角定义如下:每个数等于它上方两数之和。
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
1.每行list可以分为三部分,第一个元素,中间元素,最后一个元素。其中第一个元素和最后一个元素都为固定值1
2.除第一行和第二行之外,其余每行的中间元素都是上一行相加的结果,第三行有一个中间元素,第四行有两个中间元素……可以得到,中间元素个数m=len(上一行) – 1.同时,m是上一行做加法的次数,所以,可以通过for … in range(m)语句迭代得到下一行的元素
程序:
# -*- coding: utf-8 -*-
def triangles():
L=[1]
while True:
yield L
L = [ L[0] ] + [ L[n]+L[n+1] for n in range(len(L)-1) ] + [ L[0] ]
结果:
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('测试失败!')
感兴趣的话可以自己试一下下面的三角:
[1]
[3, 3]
[5, 6, 5]
[7, 11, 11, 7]
[9, 18, 22, 18, 9]
[11, 27, 40, 40, 27, 11]
[13, 38, 67, 80, 67, 38, 13]
[15, 51, 105, 147, 147, 105, 51, 15]
[17, 66, 156, 252, 294, 252, 156, 66, 17]
[19, 83, 222, 408, 546, 546, 408, 222, 83, 19]
程序:
# -*- coding: utf-8 -*-
def triangles():
L = [1]
while(1):
a = 0
yield L
a=a+1
L = [ L[0]+2*a ] + [ L[n]+L[n+1] for n in range( len(L)-1 ) ] + [ L[0]+2*a ]