Python练习 杨辉三角

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python练习 杨辉三角相关的知识,希望对你有一定的参考价值。



One:

triangle = [[1], [1, 1]]
num = 7
for n in range(2, num):
    pre = triangle[n - 1]
    cur = [1]
    for j in range(0, n - 1):
        cur.append(pre[j] + pre[j + 1])
    cur.append(1)
    triangle.append(cur)
for i in triangle:
    print(‘ ‘ * (6 - int(triangle.index(i))), i)


Two:

triangle = [
    [1],
    [1, 1]
]  # 初始化一个有0,1两个索引的嵌套列表
line = 11  # 打印几行杨辉三角
for index in range(2, line):  # 从主列表第2个索引开始
    previous = triangle[index - 1]  # 第n行有n个索引,比如第三行,从0,1,2 共三个,最后一个索引是行号减1
    current = [1]  # 放一个只有头部 1的新列表
    for index2 in range(0, index - 1):
        current.append(previous[index2] + previous[index2 + 1])  # 迭代把0和1相加结果追加到列表,1和2,2和3,3和4,边界是line,行号就是有line个索引
    current.append(1)  # 追加尾部的1
    triangle.append(current)  # 把新的行(新的列表)追加到主列表
for lst in triangle:
    print(‘ ‘ * (line - int(triangle.index(lst))), lst)


Three:

triangle = []
line = 11
for index in range(0, line):
    if index == 0:
        triangle.append([1])
    else:
        previous = triangle[index-1]
        current = [1]
        for index2 in range(0,index-1):
            current.append(previous[index2]+previous[index2+1])
        current.append(1)
        triangle.append(current)
for lst in triangle:
    print(‘ ‘*(line-int(triangle.index(lst))),lst)


Four:

n = 7
oldline = []
newline =[1]
length = 0
print(newline)
for i in range(1, n):
    oldline = newline.copy()
    oldline.append(0)
    print(oldline)
    newline.clear()
    offset = 0
    while offset <= i:
        newline.append(oldline[offset-1] + oldline[offset])
        offset += 1
    print(newline)


five:

triangle = []
n = 10
count = 0
for line in range(1, n+1):
    current = [1] * line
    for j in range(1, line):
        count += 1
        if j == 1:
            continue
        else:
            current[j-1] = triangle[-1][j - 2] + triangle[-1][j - 1]
    triangle.append(current)
print(triangle)
for j in triangle:
    print(j)
print(count)






以上是关于Python练习 杨辉三角的主要内容,如果未能解决你的问题,请参考以下文章

Python 中使用 forwhile 循环打印杨辉三角练习(列表索引练习)。

Python练习 杨辉三角

Python练习题——用列表的方法输出杨辉三角

python杨辉三角实现练习

python3练习-杨辉三角/帕斯卡三角形

python输入输出练习,运算练习和turtle练习