Discuss / Python / 杨辉三角

杨辉三角

Topic source

细雨小巷

#1 Created at ... [Delete] [Delete and Lock User]

-- coding: utf-8 --

def triangles(): yield [1] # n = 0 第一行 yield [1, 1] # n = 1 第二行

b, n, old = 0, 2, [1, 1] # 从第三行开始 n = 2

newL = list(range(n + 1))
while b < n:
    if b == 0:
        newL[0] = 1
    else:
        newL[b] = old[b] + old[b-1]
    b = b + 1
    if b == n:
        newL[n] = 1
        yield newL

        b, n, old = 0, n + 1, newL[::] # 初始化下一行需要的变量

        newL = list(range(n + 1))

  • 1

Reply