-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
56 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,44 @@ | ||
#!/usr/bin/python3 | ||
""" | ||
0-pascal_triangle | ||
Create a function def pascal_triangle(n): that returns a list of lists of | ||
integers representing the Pascal’s triangle of n: | ||
Returns an empty list if n <= 0 | ||
You can assume n will be always an integer | ||
""" | ||
|
||
|
||
def pascal_triangle(n): | ||
if n <= 0: | ||
return [] | ||
""" | ||
Creates a list of lists of integers representing Pascal's triangle | ||
parameters: | ||
n [int]: | ||
the number of rows of Pascal's triangle to recreate | ||
return: | ||
[list of lists of ints]: | ||
representation of Pascal's triangle | ||
""" | ||
if type(n) is not int: | ||
raise TypeError("n must be an integer") | ||
triangle = [] | ||
for i in range(n): | ||
if i == 0: | ||
triangle.append([1]) | ||
if n <= 0: | ||
return triangle | ||
previous = [1] | ||
for row_index in range(n): | ||
rowlist = [] | ||
if row_index == 0: | ||
rowlist = [1] | ||
else: | ||
row = [1] | ||
for j in range(1, i): | ||
row.append(triangle[i - 1][j - 1] + triangle[i - 1][j]) | ||
row.append(1) | ||
triangle.append(row) | ||
|
||
for i in range(row_index + 1): | ||
if i == 0: | ||
rowlist.append(0 + previous[i]) | ||
elif i == (row_index): | ||
rowlist.append(previous[i - 1] + 0) | ||
else: | ||
rowlist.append(previous[i - 1] + previous[i]) | ||
previous = rowlist | ||
triangle.append(rowlist) | ||
return triangle |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
#!/usr/bin/python3 | ||
""" | ||
0-pascal_triangle | ||
""" | ||
|
||
|
||
def pascal_triangle(n): | ||
if n <= 0: | ||
return [] | ||
|
||
triangle = [] | ||
for i in range(n): | ||
if i == 0: | ||
triangle.append([1]) | ||
else: | ||
row = [1] | ||
for j in range(1, i): | ||
row.append(triangle[i - 1][j - 1] + triangle[i - 1][j]) | ||
row.append(1) | ||
triangle.append(row) | ||
|
||
return triangle |