递归Pascal';s三角形(Python)
我不确定我的代码在python中使用递归pascal三角形时犯了什么错误。任何帮助都将不胜感激:)递归Pascal';s三角形(Python),python,recursion,pascals-triangle,Python,Recursion,Pascals Triangle,我不确定我的代码在python中使用递归pascal三角形时犯了什么错误。任何帮助都将不胜感激:) 您在构建新线的循环中遇到了一些混乱范围(1,最后一行[-1])没有意义;您希望迭代最后一行的索引,即range(len(last_row))。您还将下一行的最后一行和最后一行混在了一起 以下是您的代码的更正版本: n = 5 def printPascal(n): Pascal_List = [] if n == 0: Pascal_List.append([1]
您在构建新线的循环中遇到了一些混乱<代码>范围(1,最后一行[-1])没有意义;您希望迭代最后一行的索引,即
range(len(last_row))
。您还将下一行的最后一行
和最后一行
混在了一起
以下是您的代码的更正版本:
n = 5
def printPascal(n):
Pascal_List = []
if n == 0:
Pascal_List.append([1])
return Pascal_List
if n == 1:
Pascal_List.append([1])
Pascal_List.append([1,1])
return Pascal_List
else:
new_row = [1]
final_r = printPascal(n - 1)
last_row = final_r[-1]
for k in range(len(last_row)-1):
new_row.append(last_row[k] + last_row[k + 1])
new_row.append(1)
final_r.append(new_row)
return final_r
print(printPascal(n))
您在构建新线的循环中遇到了一些混乱<代码>范围(1,最后一行[-1])没有意义;您希望迭代最后一行的索引,即
range(len(last_row))
。您还将下一行的最后一行
和最后一行
混在了一起
以下是您的代码的更正版本:
n = 5
def printPascal(n):
Pascal_List = []
if n == 0:
Pascal_List.append([1])
return Pascal_List
if n == 1:
Pascal_List.append([1])
Pascal_List.append([1,1])
return Pascal_List
else:
new_row = [1]
final_r = printPascal(n - 1)
last_row = final_r[-1]
for k in range(len(last_row)-1):
new_row.append(last_row[k] + last_row[k + 1])
new_row.append(1)
final_r.append(new_row)
return final_r
print(printPascal(n))
有一种更好的方法可以使用Pascal三角形的一般公式(n选择k),但我将不讨论这个问题 看看你的代码,我猜你是想把前一行的前两个数字相加,得到下一个数字 在您的
else
条件下更改并替换为:
#It should be length instead.
for k in range(1, len(last_row)):
new_row.append(last_row[k] + last_row[k - 1])
#You need to add the 1 at the end
new_row.append(1)
有一种更好的方法可以使用Pascal三角形的一般公式(n选择k),但我将不讨论这个问题 看看你的代码,我猜你是想把前一行的前两个数字相加,得到下一个数字 在您的
else
条件下更改并替换为:
#It should be length instead.
for k in range(1, len(last_row)):
new_row.append(last_row[k] + last_row[k - 1])
#You need to add the 1 at the end
new_row.append(1)
已经解释了for
循环的问题,无需重复。但是,请注意,您可以使代码简单得多:
- 无需对
情况进行特殊处理n==1
- 通过在最后一行填充零,可以使第二部分更加简单
def printPascal(n):
if n == 0:
return [[1]]
else:
final_r = printPascal(n - 1)
last = [0] + final_r[-1] + [0] # note: this does not modify final_r
new_row = [last[k] + last[k - 1] for k in range(1, len(last))]
return final_r + [new_row]
已经解释了for
循环的问题,无需重复。但是,请注意,您可以使代码简单得多:
- 无需对
情况进行特殊处理n==1
- 通过在最后一行填充零,可以使第二部分更加简单
def printPascal(n):
if n == 0:
return [[1]]
else:
final_r = printPascal(n - 1)
last = [0] + final_r[-1] + [0] # note: this does not modify final_r
new_row = [last[k] + last[k - 1] for k in range(1, len(last))]
return final_r + [new_row]
非常感谢。你是一个传奇:谢谢你!你是一个传奇人物:你需要问一个特定的问题,而不是说“这是我的代码。它不工作。请为我调试它”。请看,您需要询问一个特定的问题,而不是仅仅说“这是我的代码。它不起作用。请为我调试它”。看见