Bkataru

Python Pascal Triangle code

Sep 12th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. #PASCAL TRIANGLE
  2. no = int(input("Enter the number of rows: "))
  3. n = 1 #variable n representes the current row
  4. while n <= no: #loop checking for each row
  5.     totalterms = n + 1 #total terms in a row
  6.     term = 0 # current term (or also known as r)
  7.     line = "" #the row in string form
  8.     n_num = 1 #n!
  9.     n_r = 1 #(n-r)!
  10.     r = 1 #r!
  11.     while term < totalterms: #calculating coefficient of each term in a row consecutively through a loop
  12.         j = 1 #j, u, and p are variables for calculating factorials
  13.         for j in range(1, n + 1): #n! calculation loop
  14.             n_num *= j
  15.         u = 1
  16.         for u in range(1, (n - term) + 1): #(n-r)! calculation loop
  17.             n_r *= u
  18.         p = 1
  19.         for p in range(1, term + 1): #r! calculation loop
  20.             r *= p
  21.         line = line + str(n_num//(n_r * r)) + " " #adding the calculated coefficient to the row one after another
  22.         term += 1
  23.         n_num = 1 #resetting the n! value for the next calculation
  24.         n_r = 1 #resetting the (n-r)! value for the next calculation
  25.         r = 1 #resetting the r! value for the next calculation
  26.     #s = n - no
  27.     s = 0
  28.     while s < (no - n): #loop to add spaces to each row so that they all form a triangle
  29.         line = " " + line
  30.         s += 1
  31.     print(line) #print the row finally
  32.     n += 1
Add Comment
Please, Sign In to add comment