MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / generate_pascal_triangle_optimized

Function generate_pascal_triangle_optimized

matrix/pascal_triangle.py:111–163  ·  view source on GitHub ↗

This function returns a matrix representing the corresponding pascal's triangle according to the given input of number of rows of Pascal's triangle to be generated. It reduces the operations done to generate a row by half by eliminating redundant calculations. :param num_rows:

(num_rows: int)

Source from the content-addressed store, hash-verified

109
110
111def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]:
112 """
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
122 >>> generate_pascal_triangle_optimized(3)
123 [[1], [1, 1], [1, 2, 1]]
124 >>> generate_pascal_triangle_optimized(1)
125 [[1]]
126 >>> generate_pascal_triangle_optimized(0)
127 []
128 >>> generate_pascal_triangle_optimized(-5)
129 Traceback (most recent call last):
130 ...
131 ValueError: The input value of 'num_rows' should be greater than or equal to 0
132 >>> generate_pascal_triangle_optimized(7.89)
133 Traceback (most recent call last):
134 ...
135 TypeError: The input value of 'num_rows' should be 'int'
136 """
137
138 if not isinstance(num_rows, int):
139 raise TypeError("The input value of 'num_rows' should be 'int'")
140
141 if num_rows == 0:
142 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 )
147
148 result: list[list[int]] = [[1]]
149
150 for row_index in range(1, num_rows):
151 temp_row = [0] + result[-1] + [0]
152 row_length = row_index + 1
153 # Calculate the number of distinct elements in a row
154 distinct_elements = sum(divmod(row_length, 2))
155 row_first_half = [
156 temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1)
157 ]
158 row_second_half = row_first_half[: (row_index + 1) // 2]
159 row_second_half.reverse()
160 row = row_first_half + row_second_half
161 result.append(row)
162
163 return result
164
165
166def benchmark() -> None:

Callers

nothing calls this directly

Calls 2

reverseMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected