问题陈述

Problem Statement:

Find and return the nth row of Pascal's triangle in the form a list. n is 0-based.

For exmaple, if n = 4, then output = [1, 4, 6, 4, 1].

To know more about Pascal's triangle: https://www.mathsisfun.com/pascals-triangle.html

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def next_row(current_row):
row = [1]
for i in range(len(current_row)):
if i == len(current_row)-1:
break
row.append(current_row[i] + current_row[i+1])
row.append(1)
return row
def nth_row_pascal(num_row):
if num_row == 0:
return [1]
if num_row == 1:
return [1, 1]
n = 2
current_row = [1, 1]
while n != num_row:
n += 1
current_row = next_row(current_row)
return next_row(current_row)

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def test_function(test_case):
n = test_case[0]
solution = test_case[1]
output = nth_row_pascal(n)
if solution == output:
print("Pass")
else:
print("Fail")

n = 0
solution = [1]
test_case = [n, solution]
test_function(test_case)

n = 1
solution = [1, 1]
test_case = [n, solution]
test_function(test_case)

n = 2
solution = [1, 2, 1]
test_case = [n, solution]
test_function(test_case)

n = 3
solution = [1, 3, 3, 1]
test_case = [n, solution]
test_function(test_case)

n = 4
solution = [1, 4, 6, 4, 1]
test_case = [n, solution]
test_function(test_case)

print(nth_row_pascal(5))