杨辉三角的几种解法

杨辉三角的几种解法

一、用列表嵌套代表杨辉三角

triangle=[[1]] 
n=8
for i in range(2,n+1):#i代表杨辉三角的行
    l1=[1]
    for j in range(2,i):
        l1.append(triangle[i-2][j-2]+triangle[i-2][j-1])#上一项相邻两数的和
    l1.append(1)
    triangle.append(l1)
print(triangle)

输出结果为 [[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]]

二、用一个列表循环使用

l1=[1]
print(l1)
for i in range(1,9):
    l2=l1
    l2.append(0)
    l1=[1]
    for j in range(i):
        l1.append(l2[j]+l2[j+1])
    print(l1)

输出结果为:
[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]
此方法中l2=l1属于列表复制,若列表数据多,循环复制则会引起垃圾回收GC,会造成卡顿,运行部流畅。
解法二变种:

n=9
l1=[]
val=1
for i in range(n):
    for j in range(1,i):
        x=val+l1[j]
        val=l1[j]
        l1[j]=x
    l1.append(1)
    print(l1)

输出结果为
[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]

三、切片

n=9
l1=[1]*n
val=1
for i in range(n):
    for j in range(1,i):
        x=val+l1[j]
        val=l1[j]
        l1[j]=x
    print(l1[:i+1])

输出结果为:
[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]

四、对称

n=10
l1=[]
for i in range(1,n):
    l1.append(1)
    val=1
    for j in range(1,(i+1)//2):#取每行的中间
        x=val+l1[j]
        val=l1[j]
        l1[j]=x
        if i!=2j+1:#如果是奇数行,中间的数被赋值一次
            l1[-j-1]=x
    print(l1)

输出结果为:
[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]

你可能感兴趣的:(杨辉三角的几种解法)