triangle = [[1],[1,1]] #定义前两列
for i in range(2,6):
row = [1]
for j in range(0,i-1):
vol = triangle[i-1][j] + triangle[i-1][j+1]
row.append(vol)
row.append(1)
triangle.append(row)
print(triangle)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
从第[2]行开始,每一个元素(不包括开头和结尾的1)都是由上一行的两个元素相加得来的。
ln[i] = l(n-1)[i-1] + l(n-1)[i]
n >= 3
triangle = []
n = 6
for i in range(n):
row=[1]
triangle.append(row)
if i == 0:
continue
for j in range(i-1):
vol = triangle[i-1][j] + triangle[i-1][j+1]
row.append(vol)
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]]
在原有基础上,将前两行加入循环中,通过判断将特例单独处理
n = 6
row = [1]
print(row)
for i in range(1,n):
newline = row.copy()
newline.insert(0,0)
newline.append(0)
row = []
for j in range(i+1):
row.append(newline[j] + newline[j+1])
print(row)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
首先去诶的那个第[0]行特例,从第[1]行开始两头加0。
从第[1]行开始,每一个元素都是由上一行的两个元素相加得来的。
计算一行输入一行。
n = 6
row = [1]
print(row)
for i in range(1,n):
newline = row.copy()
newline.append(0)
row = []
for j in range(i+1):
row.append(newline[j-1] + newline[j])
print(row)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
通过负索引来进行相加
n = 6
for i in range(n):
row = [1]*(i+1)
for j in range(1,i//2+1):
vol = newline[j] + newline[j-1]
row[j] = vol
if i != 2*j:
row[-j-1] = vol
newline = row
print(row)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
从运行结果可以看出当一行的元素数为偶时,每一个元素都有对称性。
素数时,则最中间的元素没有。
所以可以通过判断,当当前元素是中间数时,不添加对称元素。
n = 6
row = [1] * n
for i in range(n):
notuse = n - i
z = 1
for j in range(1,i//2+1):
val = z + row[j]
row[j],z = val,row[j]
if i != 2*j:
row[-j-notuse] = 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]
直接生成一个长度合适的列表,通过切片的方式打印。
从运行结果可以看出,从第[2]行开始,第二个元素覆盖前一行第二个元素,一次覆盖,并在最后加1