Python function that prints out the first n rows of Pascal’s triangle

 Pascal’s triangle:-

In mathematicsPascal's triangle is a triangular array of the binomial coefficients that arises in probability theory, combinatorics, and algebra. In much of the Western world, it is named after the French mathematician Blaise Pascal, although other mathematicians studied it centuries before him in India.



 method 1:-

def pascal_triangle(num):

   trow = [1]
   y = [0]
   for x in range(max(num,0)):
      print(trow)
      trow=[l+r for l,r in zip(trow+y, y+trow)]
   return num>=1
pascal_triangle(5)

output:-
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
>>> 
method 2:-

# 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()
output:-
     1 
     1 1 
    1 2 1 
   1 3 3 1 
  1 4 6 4 1 
>>> 

method 3:-
num = int(input("Enter the number: "))  
list1 = [] #an empty list  
for i in range(num):  
  list1.append([])  
  list1[i].append(1)  
  for j in range(1, i):  
    list1[i].append(list1[i - 1][j - 1] + list1[i - 1][j])  
  if(num != 0):  
    list1[i].append(1)  
for i in range(num):  
  print(" " * (num - i), end = " ", sep = " ")  
  for j in range(0, i + 1):  
    print('{0:6}'.format(list1[i][j]), end = " ", sep = " ")  
  print()  
output:-
Enter the number: 7
             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 
>>> 

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post