三项式三角形 (Python)

Trinomial triangle (Python)

出于对学习 Python 的兴趣,我在遇到一个练习时停下来:

Consider the expression (1 + x + x^2)^n and write a program which calculates a modified Pascal’s triangle (known as the trinomial triangle) for the coefficients of its expansion. Can you come up with a simple rule (and prove that it works!) which would enable you to write down the coefficients of this triangle?

所以,我正在尝试编写一个代码,从用户输入中打印出 trinomial triangle。这是我到目前为止的代码:

import math

rows = 0 #We count how many rows we print

#We define a function that will calculate the triangle.
def calc(n, r):
    if r == 0 or r == n:
        return 1
    return int(math.pow(1 + r + math.pow(r, 2), n))

#We define a function that append the values in an array.
def triangle(rows):
    result = [] #We need an array to collect our results.
    for count in range(rows): #For each count in the inputted rows
        row = [] #We need a row element to collect the rows.
        for element in range(count + 1):
            #We add the function calculation to the row array.
            row.append(calc(count, element))
        #We add the row(s) to the result array.
        result.append(row)
    return result

number = int(input("How many rows do you want printed? "))

#We can now print the results:
for row in triangle(number):
    rows += 1 #We add one count to the amount of rows
    print("Row %d: %s" % (rows, row)) #Print everything

哪个returns

How many rows do you want printed? 5
Row 1: [1]
Row 2: [1, 1]
Row 3: [1, 9, 1]
Row 4: [1, 27, 343, 1]
Row 5: [1, 81, 2401, 28561, 1]

据我了解,预期结果应该是:

1
1   1   1
1   2   3   2   1
1   3   6   7   6   3   1
1   4   10  16  19  16  10  4  1

我不知道如何从这里开始。任何能为我指明正确方向的建议都将不胜感激。

在帕斯卡三角的通常二项式版本中,我们可以通过将紧靠其上方的两个条目相加来计算一行中的每个值。在三项式版本中,我们添加了三个条目。这个证明并不难,所以我会让你弄清楚。 ;)

这是 Python 中的一种方法。

row = [1]
for i in range(8):
    print(row)
    row = [sum(t) for t in zip([0,0]+row, [0]+row+[0], row+[0,0])]

输出

[1]
[1, 1, 1]
[1, 2, 3, 2, 1]
[1, 3, 6, 7, 6, 3, 1]
[1, 4, 10, 16, 19, 16, 10, 4, 1]
[1, 5, 15, 30, 45, 51, 45, 30, 15, 5, 1]
[1, 6, 21, 50, 90, 126, 141, 126, 90, 50, 21, 6, 1]
[1, 7, 28, 77, 161, 266, 357, 393, 357, 266, 161, 77, 28, 7, 1]

只是为了让我想要显示的线出现,例如 income 2 只显示三角形的第二条线,即 1 1 1