Skip to content

Commit c4f6fa5

Browse files
authored
Update pascals_triangle.py
1 parent fede4f1 commit c4f6fa5

File tree

1 file changed

+42
-37
lines changed

1 file changed

+42
-37
lines changed
Lines changed: 42 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,47 @@
1-
""" Generate Pascal's Triangle.
1+
"""
2+
Generate Pascal's Triangle.
23
3-
Python doctest can be run with the following command: python -m doctest -v pascals_triangle.py
4+
Reference: https://en.wikipedia.org/wiki/Pascal%27s_triangle
45
5-
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
6+
Python doctest can be run with the following command:
7+
python -m doctest -v pascals_triangle.py
68
9+
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
710
In Pascal's triangle, each number is the sum of the two numbers directly above it.
8-
9-
Example Input: numRows = 5 Output: [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1] ] """
10-
11-
class Solution(object): def generate(self, numRows): """ Generate the first numRows of Pascal's triangle.
12-
13-
Args:
14-
numRows (int): The number of rows to generate.
15-
16-
Returns:
17-
list[list[int]]: Pascal's triangle as a list of lists.
18-
19-
Examples:
20-
>>> solution = Solution()
21-
>>> solution.generate(5)
22-
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
23-
>>> solution.generate(1)
24-
[[1]]
25-
>>> solution.generate(0)
26-
[]
27-
"""
28-
ans = []
29-
for i in range(numRows):
30-
# Initialize the row with 1s
31-
row = [1] * (i + 1)
32-
33-
# Compute inner elements by summing elements from the previous row
34-
for j in range(1, i):
35-
row[j] = ans[i-1][j-1] + ans[i-1][j]
11+
"""
12+
13+
class Solution:
14+
def generate(self, num_rows: int) -> list[list[int]]:
15+
"""
16+
Generate the first num_rows of Pascal's triangle.
17+
18+
Args:
19+
num_rows (int): The number of rows to generate.
20+
21+
Returns:
22+
list[list[int]]: Pascal's triangle as a list of lists.
23+
24+
Examples:
25+
>>> solution = Solution()
26+
>>> solution.generate(5)
27+
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
28+
>>> solution.generate(1)
29+
[[1]]
30+
>>> solution.generate(0)
31+
[]
32+
"""
33+
ans: list[list[int]] = []
34+
for i in range(num_rows):
35+
# Initialize the row with 1s
36+
row = [1] * (i + 1)
3637

37-
ans.append(row)
38-
return ans
39-
if name == "main":
40-
import doctest
41-
42-
doctest.testmod()
38+
# Compute inner elements by summing elements from the previous row
39+
for j in range(1, i):
40+
row[j] = ans[i-1][j-1] + ans[i-1][j]
41+
42+
ans.append(row)
43+
return ans
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()

0 commit comments

Comments
 (0)