Skip to content

Commit 0e59bcd

Browse files
authored
Create pascals_Triangle.py
1 parent 2c15b8c commit 0e59bcd

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
""" Generate Pascal's Triangle.
2+
3+
Python doctest can be run with the following command: python -m doctest -v pascals_triangle.py
4+
5+
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
6+
7+
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]
36+
37+
ans.append(row)
38+
return ans
39+
if name == "main":
40+
import doctest
41+
42+
doctest.testmod()

0 commit comments

Comments
 (0)