Pascal在python中的三角形

Don*_*rko 4 python

所以我正在制作Pascal的三角形,我无法弄清楚为什么这段代码不起作用.它打印出这样的东西

[]
[1]
[1, 2]
[1, 3, 3]
[1, 4, 6, 4]
[1, 5, 10, 10, 5]
[1, 6, 15, 20, 15, 6]
[1, 7, 21, 35, 35, 21, 7]
[1, 8, 28, 56, 70, 56, 28, 8]
[1, 9, 36, 84, 126, 126, 84, 36, 9]
Run Code Online (Sandbox Code Playgroud)

这几乎是正确的,但它似乎值似乎是行数太高,所以1,2,如果算上2作为第一行和1为第0行,2为1个值太高,因为它是在第一行,应该是1,1.下一行应该是1,2,1,第一个值是正确的,但是下一个值是1个值太高而后一个值是2个值太高.

我尝试过像append(ai)这样的东西,但似乎不起作用,你怎么能正确打印呢?

def triangle(rows):

    for rownum in range (rows):
        newValue=1
        PrintingList = list()
        for iteration in range (rownum):
            newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 )
            PrintingList.append(int(newValue))
        print(PrintingList)
    print()
Run Code Online (Sandbox Code Playgroud)

提前致谢.

JAB*_*JAB 10

我会PrintingList = list()改为PrintingList = [newValue].

triangle(10) 然后给你以下:

[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]
Run Code Online (Sandbox Code Playgroud)

哪个是有效的Pascal三角形.