Skip to content

Commit 23772e7

Browse files
authored
Update pascal_triangle.py
1 parent b1e0e3f commit 23772e7

1 file changed

Lines changed: 39 additions & 49 deletions

File tree

matrix/pascal_triangle.py

Lines changed: 39 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
"""
2-
This implementation demonstrates how to generate the elements of a Pascal's triangle.
3-
The element havingva row index of r and column index of c can be derivedvas follows:
4-
triangle[r][c] = triangle[r-1][c-1]+triangle[r-1][c]
2+
This implementation demonstrates how to generate the elements of Pascal's Triangle.
3+
An element with row index r and column index c can be derived as:
4+
triangle[r][c] = triangle[r-1][c-1] + triangle[r-1][c]
55
6-
A Pascal's triangle is a triangular array containing binomial coefficients.
6+
Pascal's Triangle is a triangular array containing binomial coefficients.
77
https://en.wikipedia.org/wiki/Pascal%27s_triangle
88
"""
99

10+
from typing import List, Callable
11+
from timeit import timeit
12+
1013

1114
def print_pascal_triangle(num_rows: int) -> None:
1215
"""
13-
Print Pascal's triangle for different number of rows
16+
Print Pascal's triangle for the specified number of rows
1417
>>> print_pascal_triangle(5)
1518
1
1619
1 1
@@ -20,7 +23,7 @@ def print_pascal_triangle(num_rows: int) -> None:
2023
"""
2124
triangle = generate_pascal_triangle(num_rows)
2225
for row_idx in range(num_rows):
23-
# Print left spaces
26+
# Print leading spaces
2427
for _ in range(num_rows - row_idx - 1):
2528
print(end=" ")
2629
# Print row values
@@ -32,9 +35,9 @@ def print_pascal_triangle(num_rows: int) -> None:
3235
print()
3336

3437

35-
def generate_pascal_triangle(num_rows: int) -> list[list[int]]:
38+
def generate_pascal_triangle(num_rows: int) -> List[List[int]]:
3639
"""
37-
Create Pascal's triangle for different number of rows
40+
Generate Pascal's triangle for the specified number of rows
3841
>>> generate_pascal_triangle(0)
3942
[]
4043
>>> generate_pascal_triangle(1)
@@ -50,49 +53,46 @@ def generate_pascal_triangle(num_rows: int) -> list[list[int]]:
5053
>>> generate_pascal_triangle(-5)
5154
Traceback (most recent call last):
5255
...
53-
ValueError: The input value of 'num_rows' should be greater than or equal to 0
56+
ValueError: Input value 'num_rows' must be >= 0
5457
>>> generate_pascal_triangle(7.89)
5558
Traceback (most recent call last):
5659
...
57-
TypeError: The input value of 'num_rows' should be 'int'
60+
TypeError: Input value 'num_rows' must be an integer
5861
"""
5962

6063
if not isinstance(num_rows, int):
61-
raise TypeError("The input value of 'num_rows' should be 'int'")
64+
raise TypeError("Input value 'num_rows' must be an integer")
6265

6366
if num_rows == 0:
6467
return []
65-
elif num_rows < 0:
66-
raise ValueError(
67-
"The input value of 'num_rows' should be greater than or equal to 0"
68-
)
68+
if num_rows < 0:
69+
raise ValueError("Input value 'num_rows' must be >= 0")
6970

70-
triangle: list[list[int]] = []
71+
triangle: List[List[int]] = []
7172
for current_row_idx in range(num_rows):
7273
current_row = populate_current_row(triangle, current_row_idx)
7374
triangle.append(current_row)
7475
return triangle
7576

7677

77-
def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]:
78+
def populate_current_row(triangle: List[List[int]], current_row_idx: int) -> List[int]:
7879
"""
7980
>>> triangle = [[1]]
8081
>>> populate_current_row(triangle, 1)
8182
[1, 1]
8283
"""
8384
current_row = [-1] * (current_row_idx + 1)
84-
# first and last elements of current row are equal to 1
85+
# First and last elements of current row are always 1
8586
current_row[0], current_row[-1] = 1, 1
8687
for current_col_idx in range(1, current_row_idx):
8788
calculate_current_element(
8889
triangle, current_row, current_row_idx, current_col_idx
8990
)
9091
return current_row
9192

92-
9393
def calculate_current_element(
94-
triangle: list[list[int]],
95-
current_row: list[int],
94+
triangle: List[List[int]],
95+
current_row: List[int],
9696
current_row_idx: int,
9797
current_col_idx: int,
9898
) -> None:
@@ -103,22 +103,19 @@ def calculate_current_element(
103103
>>> current_row
104104
[1, 2, 1]
105105
"""
106-
above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1]
107-
above_to_right_elt = triangle[current_row_idx - 1][current_col_idx]
108-
current_row[current_col_idx] = above_to_left_elt + above_to_right_elt
106+
above_left = triangle[current_row_idx - 1][current_col_idx - 1]
107+
above_right = triangle[current_row_idx - 1][current_col_idx]
108+
current_row[current_col_idx] = above_left + above_right
109109

110110

111-
def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]:
111+
def generate_pascal_triangle_optimized(num_rows: int) -> List[List[int]]:
112112
"""
113-
This function returns a matrix representing the corresponding pascal's triangle
114-
according to the given input of number of rows of Pascal's triangle to be generated.
115-
It reduces the operations done to generate a row by half
116-
by eliminating redundant calculations.
117-
118-
:param num_rows: Integer specifying the number of rows in the Pascal's triangle
119-
:return: 2-D List (matrix) representing the Pascal's triangle
120-
121-
Return the Pascal's triangle of given rows
113+
Returns a matrix representing Pascal's triangle.
114+
Reduces operations by half by eliminating redundant calculations.
115+
116+
:param num_rows: Number of rows in the Pascal's triangle
117+
:return: 2D list representing the Pascal's triangle
118+
122119
>>> generate_pascal_triangle_optimized(3)
123120
[[1], [1, 1], [1, 2, 1]]
124121
>>> generate_pascal_triangle_optimized(1)
@@ -128,29 +125,27 @@ def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]:
128125
>>> generate_pascal_triangle_optimized(-5)
129126
Traceback (most recent call last):
130127
...
131-
ValueError: The input value of 'num_rows' should be greater than or equal to 0
128+
ValueError: Input value 'num_rows' must be >= 0
132129
>>> generate_pascal_triangle_optimized(7.89)
133130
Traceback (most recent call last):
134131
...
135-
TypeError: The input value of 'num_rows' should be 'int'
132+
TypeError: Input value 'num_rows' must be an integer
136133
"""
137134

138135
if not isinstance(num_rows, int):
139-
raise TypeError("The input value of 'num_rows' should be 'int'")
136+
raise TypeError("Input value 'num_rows' must be an integer")
140137

141138
if num_rows == 0:
142139
return []
143-
elif num_rows < 0:
144-
raise ValueError(
145-
"The input value of 'num_rows' should be greater than or equal to 0"
146-
)
140+
if num_rows < 0:
141+
raise ValueError("Input value 'num_rows' must be >= 0")
147142

148-
result: list[list[int]] = [[1]]
143+
result: List[List[int]] = [[1]]
149144

150145
for row_index in range(1, num_rows):
151146
temp_row = [0] + result[-1] + [0]
152147
row_length = row_index + 1
153-
# Calculate the number of distinct elements in a row
148+
# Calculate number of distinct elements in row
154149
distinct_elements = sum(divmod(row_length, 2))
155150
row_first_half = [
156151
temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1)
@@ -162,18 +157,13 @@ def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]:
162157

163158
return result
164159

165-
166160
def benchmark() -> None:
167161
"""
168-
Benchmark multiple functions, with three different length int values.
162+
Benchmark functions with different input sizes
169163
"""
170-
from collections.abc import Callable
171-
from timeit import timeit
172-
173164
def benchmark_a_function(func: Callable, value: int) -> None:
174165
call = f"{func.__name__}({value})"
175166
timing = timeit(f"__main__.{call}", setup="import __main__")
176-
# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
177167
print(f"{call:38} -- {timing:.4f} seconds")
178168

179169
for value in range(15): # (1, 7, 14):

0 commit comments

Comments
 (0)