tobulos1 tobulos1 - 3 years ago 246
Python Question

Trinomial triangle (Python)

As part of my interest in learning Python, I've hit a stop when coming across an exercise that states:


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?


So, I'm trying to write a code that prints out the trinomial triangle from a user input. This is the code I have so far:

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


which 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]


And as I understand it, the expected result should be:

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


I don't exactly know how to proceed from here. Any suggestions to point me in the right direction would be appreciated.

Answer Source

In the usual binomial version of Pascal's Triangle we can compute each value in a row by adding the two entries immediately above it. In the trinomial version we add three entries. The proof of this isn't hard, so I'll let you figure it out. ;)

Here's one way to do that in 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])]

output

[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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download