Python Program to Print Trinomial Triangle

In this article, we will learn how to print a trinomial triangle in Python. A Trinomial triangle is a variety of Pascal’s triangle. The distinction between the two is that a value in the Trinomial triangle is the sum of the three (instead of the two in Pascal’s triangle) values above it.

Examples

Input: n = 6
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

Input: n = 3
Output:
1 
1 1 1
1 2 3 2 1

Trinomial Triangle in Python

We will solve this problem using a recursive approach.

1. Firstly create a function trinomialTriangle to print the trinomial triangle

  • Iterate i from range (0, n) as an outer loop.
  • Now, iterate j from range (-i, 1) as an inner loop that prints the first half of the trinomial triangle by calling the function trinomialValue(i, j).
  • Iterate j from range(1, i+1) as an inner loop that prints the second half of the trinomial triangle by calling the function trinomialValue(i, j).

2. Create a function trinomialValue() that generates the values of the trinomial triangle.

  • Check the corner cases when both i and j are equal to zero if satisfy return 1.
  • If j < -i or j > i then return 0.
  • Else recursively call the trinomialValue(i-1, j-1)+trinomialValue(i-1, j)+trinomialValue(i-1, j+1) and return its value.
def trinomialValue(i, j):
    if i == 0 and j == 0:
        return 1

    if j < -i or j > i:
        return 0

    return (trinomialValue(i-1, j-1)+trinomialValue(i-1, j)+trinomialValue(i-1, j+1))
def trinomialTriangle(n):
    for i in range(n):
# print first half of triangle
        for j in range(-i, 1):
            print(trinomialValue(i, j), end = " ")
# print second half of triangle
        for j in range(1, i+1):
            print(trinomialValue(i, j), end =" ")
        print()
n = int(input("Enter the n value: "))
print("Trinomial Triangle")
trinomialTriangle(n)

Output

Enter the n value: 7
Trinomial Triangle
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

Leave a Reply

Your email address will not be published.