python练习(4)——打印杨辉三角

#杨辉三角,后面补1,中间计算累加次数
n = 6
triangle = []
for i in range(n):
    row = [1]
    triangle.append(row)
    if i == 0:
        continue
    pre = triangle[i-1]
    for j in range(1,i):
        row.append(pre[j-1]+pre[j])
    row.append(1)
print(triangle)

#杨辉三角,后补零,前面用负索引[-1]
n = 6 
row = [1]
print(row)
for i in range(1,n):
    nextRow = []
    row.append(0)
    for j in range(i+1):
        nextRow.append(row[j-1]+row[j])
    print(nextRow)

    row = nextRow

#杨辉三角,每一行一次创建,对称性
n = 6
triangle = []
for i in range(n):
    row = [1]*(i+1)
    triangle.append(row)
    pre = triangle[i-1]
    for j in range(1,i//2+1):
        val = pre[j-1]+pre[j]
        row[j] = val
        if j != 2*i:
            row[-j-1] = val
print(triangle)
#杨辉三角,只创建一行,最大行,在原有基础上更改,对称性赋值,最后切片
n = 6
row = [1]*n
for i in range(n):
    z = 1
    for j in range(1,i):
        if j <= i//2:
            row[j],z =z+row[j],row[j]
        else:
            row[j] = row[-j-n+i]
    print(row[:i+1])
#杨辉三角,只创建一行,最大行,在原有基础上更改,对称性,一次循环赋值两次,减少循环次数,最后切片
n = 6
row = [1]*n
for i in range(n):
    z = 1
    for j in range(1,i//2+1):
        row[j],z = row[j] + z,row[j]
        if j != 2*i:
            row[-j-n+i] = row[j]
    print(row[:i+1])

 

你可能感兴趣的:(Python,算法练习)