本文主要介绍了使用列表List来实现杨辉三角的多种方法,来加深对List函数的理解
1,热身~只打印前六行
lst0=[1]
lst1=[1,1]
print(lst0,lst1,sep='\n')
pre=lst1
for i in range(2,6):
newline=[1]
for j in range(i-1):
line=pre[j]+pre[j+1]
newline.append(line)
newline.append(1)
print(newline)
pre = newline
实现结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
2,下一行依赖上一行所有元素,是上一行所有元素的两两相加的和,再在两头各加1
triangle = [[1],[1,1]]
n = 6
for i in range(2,n):
newline = [1]
pre = triangle[i-1] #取第二个元素[1,1],同时也是为每次循环取上一个列表
for j in range(i-1):
val = pre[j] + pre[j+1]
newline.append(val)
newline.append(1)
triangle.append(newline)
print(triangle)
#实现结果:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
3,不给定[1]和[1,2]的解决办法
triangle=[]
n = 6
for i in range(n):
row = [1]
triangle.append(row)
if i==0:
continue
for j in range(i-1):
row.append(triangle[i-1][j]+triangle[i-1][j+1])
row.append(1)
print(triangle)
#实现结果:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
4,补0法之两端补0
#补两个0
n = 6
pre = [1] #确定第一行
print(pre)
pre.insert(0,0)
pre.append(0) #[0,1,0]
for i in range(1,n):
newline = [] #预先准备一个空列表
for j in range(i+1): #代入一个具体的数确定循环次数
val = pre[j] + pre[j+1]
newline.append(val)
print(newline)
pre = newline
pre.insert(0,0) #打印之后再在首尾加0
pre.append(0)
#打印结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
5,补0法之尾端补0:
#补1个0
n = 6
pre = [1]
print(pre)
pre.append(0) #[1,0]
for i in range(1,n):
newline = []
for j in range(i+1):
val=pre[j] + pre[j-1]
newline.append(val)
print(newline)
pre = newline
pre.append(0)
#打印结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
6,补0法之使用while循环:
#方法二-while
n = 6
newline = [1] # 相当于计算好的第一行
print(newline)
for i in range(1, n):
oldline = newline.copy() # 浅拷贝并补0
oldline.append(0) # 尾部补0相当于两端补0
newline.clear() # 使用append,所以要清除
offset = 0
while offset <= i:
newline.append(oldline[offset-1] + oldline[offset])
offset += 1
print(newline)
7,采用对称思想
triangle = []
n = 6
for i in range(n):
row = [1] * (i+1) #一次性开辟
triangle.append(row)
for j in range(1,i//2+1): #i=2时才能进来
#print(i,j)
val = triangle[i-1][j-1] + triangle[i-1][j]
row[j] = val
if i != 2*j: #奇数个数的中点跳过
row[-j-1] = val
print(triangle)
#输出结果:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
8,在对称思想的基础上,一次性开辟足够的空间,更有效率,并且更简洁
n = 6
row = [1] * n #一次性开辟足够的空间
for i in range(n):
offset = n - i
z = 1 #因为会有覆盖影响计算,所以引入一个临时变量
for j in range(1,i//2+1): #dui chen xing
val = z + row[j]
row[j], z = val, row[j]
if i != 2*j:
row[-j-offset] = val
print(row[:i+1])
#输出结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]