Advertisement
acclivity

pyPascalsTriangle

Jan 30th, 2021
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. # Pascal's Triangle
  2. # Mike Kerry - 30-Jan-2021 - acclivity2@gmail.com
  3.  
  4. nrows = int(input("\nHow many rows of Pascal's Triangle would you like to print? "))
  5. nrows = min(nrows, 20)      # restrict it to 20 rows max
  6. print()
  7.  
  8. row = [0 for _ in range(nrows + nrows + 1)]  # For convenience, we use a row length twice as long as the no. of rows
  9.  
  10. tri = [row.copy() for _ in range(nrows)]     # We have to use copy() or else we get the same physical row repeated
  11.  
  12. tri[0][nrows] = 1           # Initialise the triangle with a centrally placed 1 in the top row
  13. maxv = 0
  14. for x in range(1, nrows):
  15.     for y in range(1, nrows + nrows):
  16.         v = tri[x-1][y-1] + tri[x-1][y+1]       # Compute the sum of 2 integers in the higher row, and either side
  17.         tri[x][y] = v
  18.         if v > maxv:
  19.             maxv = v                # Keep a note of the largest integer encountered
  20.  
  21. width = len(str(maxv))              # find the width required to accommodate the largest integer
  22. for row in tri:
  23.     for x in range(nrows + nrows):
  24.         s = str(row[x])
  25.         if s == "0":                        # 0 entries in our triangle become spaces
  26.             s = " "
  27.         print(s.ljust(width), end="")       # print each integer (or space) with equal width
  28.     print()
  29.  
  30.  
  31. # Results:-
  32. # How many rows of Pascal's Triangle would you like to print? 13
  33. #
  34. #                                        1
  35. #                                     1     1
  36. #                                  1     2     1
  37. #                               1     3     3     1
  38. #                            1     4     6     4     1
  39. #                         1     5     10    10    5     1
  40. #                      1     6     15    20    15    6     1
  41. #                   1     7     21    35    35    21    7     1
  42. #                1     8     28    56    70    56    28    8     1
  43. #             1     9     36    84    126   126   84    36    9     1
  44. #          1     10    45    120   210   252   210   120   45    10    1
  45. #       1     11    55    165   330   462   462   330   165   55    11    1
  46. #    1     12    66    220   495   792   924   792   495   220   66    12    1
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement