-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascals-triangle.py
More file actions
38 lines (32 loc) · 1.11 KB
/
pascals-triangle.py
File metadata and controls
38 lines (32 loc) · 1.11 KB
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
36
37
38
#!/usr/bin/env python3
#Created by PepeBigotes
def print_pascals_triangle(x: int):
# Part 1: 2D list (of int lists)
ints_triangle = [[1],]
while len(ints_triangle) < x:
newrow = []
last_row = ints_triangle[-1]
idx1 = -1 ; idx2 = 0
for i in last_row + [0,]: # Just to avoid using range(len())
if idx1 == -1: num1 = 0
else: num1 = last_row[idx1]
try: num2 = last_row[idx2]
except IndexError: num2 = 0
newrow.append(int(num1 + num2))
idx1 += 1 ; idx2 += 1
ints_triangle.append(newrow)
# Part 2: list of centered strings
str_triangle = []
for row in ints_triangle:
string = ""
for i in row: string += str(i) + ' '
str_triangle.append(string)
bottom_lenght = len(str_triangle[-1])
for enum in enumerate(str_triangle): str_triangle[enum[0]] = enum[1].center(bottom_lenght)
# Part 3: actual print
for row in str_triangle: print(row)
if __name__ == "__main__":
import sys
try: x = int(sys.argv[1])
except IndexError: x = 10
print_pascals_triangle(x)