Write a program to print Pascal's Triangle in Python

In this article, TipsMake.com will learn with you how to write a program to print Pascal's Triangle in Python.

Problem : Write a program to print Pascal's Triangle with a given number of rows.

For example : The number of rows is 5, then Pascal's Triangle will be printed as follows:

Input: n = 5 Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

Pascal's triangle is also a question frequently used by large companies when recruiting programmers. In this article, TipsMake.com will learn with you how to write a program to print Pascal's Triangle in Python.

Method 1: Use the formula nCr ie n!/(nr)!r!

After using the nCr formula, the graphical representation becomes:

 0C0 1C0 1C1 2C0 2C1 2C2 3C0 3C1 3C2 3C3

Algorithm:

  1. Get the number of rows to be printed, let's say it is n.
  2. Do the outer iteration i from 0 to n times to print the rows.
  3. Do the inner iteration for j from 0 to (N-1).
  4. Print a space "".
  5. Close inner loop (j loop) //required for left spacing.
  6. Do the inner iteration for j from 0 to i.
  7. Print nCr of i and j.
  8. Close the inner loop.
  9. Print the newline character (n) after each inner iteration.

Here is sample code:

# Print Pascal's Triangle in Python from math import factorial # input n n = 5 for i in range(n): for j in range(n-i+1): # for left spacing print(end=" ") for j in range(i+1): # nCr = n!/((n-r)!*r!) print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ") # for new line print()

Method 2:

We can optimize the above code using the following binomial coefficient concept, the i-th item in a line is the binomial coefficient C(line, i) and all lines start with the value 1. Here , we have to implement the idea of ​​computing C(line, i) using C(line, i-1).

The sample code is as follows:

# Print Pascal's Triangle in Python # input n n = 5 for i in range(1, n+1): for j in range(0, n-i+1): print(' ', end='') # first element is always 1 C = 1 for j in range(1, i+1): # first value in a line is always 1 print(' ', C, sep='', end='') # using Binomial Coefficient C = C * (i - j) // j print()

Method 3:

This is the most optimal way to print Pascal triangle. This method is based on powers of 11.

11**0 = 1 11**1 = 11 11**2 = 121 11**3 = 1331

The sample code is as follows:

# Print Pascal's Triangle in Python # input n n = 5 # iterarte upto n for i in range(n): # adjust space print(' '*(n-i), end='') # compute power of 11 print(' '.join(map(str, str(11**i))))

However, the disadvantage is that this method can only be applied up to n=5.

TipsMake.com hopes that this article will be useful to you.

« PREV
NEXT »