Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Pascal's Triangle
- # Mike Kerry - 30-Jan-2021 - acclivity2@gmail.com
- nrows = int(input("\nHow many rows of Pascal's Triangle would you like to print? "))
- nrows = min(nrows, 20) # restrict it to 20 rows max
- print()
- row = [0 for _ in range(nrows + nrows + 1)] # For convenience, we use a row length twice as long as the no. of rows
- tri = [row.copy() for _ in range(nrows)] # We have to use copy() or else we get the same physical row repeated
- tri[0][nrows] = 1 # Initialise the triangle with a centrally placed 1 in the top row
- maxv = 0
- for x in range(1, nrows):
- for y in range(1, nrows + nrows):
- v = tri[x-1][y-1] + tri[x-1][y+1] # Compute the sum of 2 integers in the higher row, and either side
- tri[x][y] = v
- if v > maxv:
- maxv = v # Keep a note of the largest integer encountered
- width = len(str(maxv)) # find the width required to accommodate the largest integer
- for row in tri:
- for x in range(nrows + nrows):
- s = str(row[x])
- if s == "0": # 0 entries in our triangle become spaces
- s = " "
- print(s.ljust(width), end="") # print each integer (or space) with equal width
- print()
- # Results:-
- # How many rows of Pascal's Triangle would you like to print? 13
- #
- # 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
- # 1 7 21 35 35 21 7 1
- # 1 8 28 56 70 56 28 8 1
- # 1 9 36 84 126 126 84 36 9 1
- # 1 10 45 120 210 252 210 120 45 10 1
- # 1 11 55 165 330 462 462 330 165 55 11 1
- # 1 12 66 220 495 792 924 792 495 220 66 12 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement