我正在做一个家庭作业,要求我使用递归函数创建一个Pascal三角形。以下是我到目前为止所处理的内容以及我的工作内容。我对Python和编程很陌生,所以我不知道从哪里开始,任何帮助都会受到赞赏!
def combination(n, k):
print((n - 1) / (k - 1)) + ((n - 1) / k)
def pascals_triangle(rows):
for row in range(rows):
answer = ""
for column in range(row + 1):
answer = answer + combination(row, column) + "\t"
print(answer)
pascals_triangle(5)
答案 0 :(得分:3)
You are not, in fact, using recursion at all in your answer. I think you are trying to code the formula nCk = (n-1)C(k-1) + (n-1)Ck. You need, therefore, to call combination
from within itself (with a guard for the "end" conditions: nC0 = nCn = 1):
def combination(n, k):
if k == 0 or k == n:
return 1
return combination(n - 1, k - 1) + combination(n - 1, k)
def pascals_triangle(rows):
for row in range( rows):
answer = ""
for column in range( row + 1):
answer = answer + str(combination(row, column)) + "\t"
print(answer)
pascals_triangle(5)
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Note that this is a spectacularly inefficient way of doing this: you are calling combination
many, many times with the same arguments each time you get a binomial coefficient. You might consider caching the coefficients you find as you go along.
The other problem with your code is that your combination
function wasn't actually returning anything, it was simply printing a value and exiting (returning None
).