-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascal_triangle.py
More file actions
35 lines (29 loc) · 1018 Bytes
/
pascal_triangle.py
File metadata and controls
35 lines (29 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Pascal's Triangle.
#
# Each entry is the sum of the two entries above it.
# Row n contains the binomial coefficients C(n,0)...C(n,n).
# Built using dynamic programming — each row derived from the previous.
def generate(n):
triangle = [[1] * (i + 1) for i in range(n + 1)]
for i in range(2, n + 1):
for j in range(1, i):
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
return triangle
def display(triangle):
n = len(triangle) - 1
width = len(str(triangle[n][n // 2]))
for i, row in enumerate(triangle):
padding = ' ' * (n - i) * ((width + 1) // 2)
print(padding + ' '.join(str(x).center(width) for x in row))
if __name__ == '__main__':
while True:
try:
n = int(input('Enter a non-negative integer: '))
if n < 0:
raise ValueError
break
except ValueError:
print('Incorrect input, try again.')
triangle = generate(n)
print()
display(triangle)