Discuss / Python / 我的解答

我的解答

Topic source

那个最多回复的答案真厉害,统一了一行中每个数字的计算。我的解答只是统一了一行中除开收尾数字的计算

def triangles():
    # 上一行的数据
    previousLine = []

    # a = 1
    n = 0
    while True:
        n = n + 1
        line = [1]
        if n == 1:
            pass
        elif n == 2:
            line.append(1)
        else:
            for index in range(n - 2):
                x = previousLine[index] + previousLine[index + 1]
                line.append(x)
            # 每行最后一个数字都是1
            line.append(1)
        yield line
        # 马上到下一行了,保存当前结果
        previousLine = line

# -*- coding: utf-8 -*-

def triangles(max):

    n=0

    L=[1]

    while n<max:

        yield(L)

        L=[0]+L+[0]

        L=[L[i]+L[i+1] for i in range(len(L)-1)]

        n=n+1        

pass

for t in triangles(10):

    print(t)


  • 1

Reply