python输出杨辉三角

知识点

1. python中的生成器 generator python生成器
2. python中-1索引表示容器的最后一个元素
代码如下:
def triangles():
    res = [1]
    while True:
        yield res
        res.append(0)
        res = [res[i] + res[i - 1] for i in range(len(res))]

n = 0
for v in triangles():
    print(v)
    n = n + 1
    if n == 10:
        break
输出结果:
[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]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
代码分析:

你可能感兴趣的:(python输出杨辉三角)