每次循环调用 Python 函数参数时如何更新它?



我在Jupyter中编写了一个函数,它接受包含帕斯卡三角形一行值的列表,然后生成以下一行。由于项目的要求,我需要从一个只包含整数1的列表开始,然后创建一个调用函数5次的循环(让我总共有6行)。

import math
def pascals_triangle(list):

nextrow = []
numrows = len(list)
numcols = len(list)

count = 0

for x in range(numcols+1):
val = ((math.factorial(numrows)) / ((math.factorial(count)) * math.factorial(numrows - count)))
nextrow.append(val)
count += 1

numrows += 1
numcols += 1
print(nextrow)

return nextrow
list = [1]
print(list)
for x in range(5):
pascals_triangle(list)

我的问题是:我无法让我的函数参数或计数以打印出所有6个递增行的方式更新。现在,它只输出相同的返回值5次。

预期输出:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

实际产出:

[1]
[1, 1]
[1, 1]
[1, 1]
[1, 1]
[1, 1]

我如何使函数每次调用时使用以前的返回值,或者让我的numrows/numcols为下一个函数调用增加?

首先,list是python原生列表对象的关键字。你永远不应该把它用作变量名,因为它不可能在以后的代码中调用列表构造函数,进行类型比较,并且通常会导致意外行为

除此之外,您错过的事情是在下一次循环迭代中将pascals_triangle的输出重新分配给函数的输入。有了这个小小的改变,它应该可以工作了

我还将print语句移到了函数之外,这样您就可以更好地控制打印的内容和时间。

import math

def pascals_triangle(lst):
nextrow = []
# numrows and numcols will be equivalent for all cases,
# and increase for each call of the function.
numrows = len(lst)
numcols = len(lst)
# count is the column we are currently looking at and will go from 1 to numcols.
count = 0
for x in range(numcols + 1):
val = ((math.factorial(numrows)) / ((math.factorial(count)) * math.factorial(numrows - count)))
nextrow.append(val)
count += 1
numrows += 1
numcols += 1
return nextrow

cur_row = [1]
for _ in range(5):
cur_row = pascals_triangle(cur_row)
print(cur_row)
import math
def pascals_triangle(list):

nextrow = []
# numrows and numcols will be equivalent for all cases, 
# and increase for each call of the function.
numrows = len(list)
numcols = len(list)

# count is the column we are currently looking at and will go from 1 to numcols.
count = 0

for x in range(numcols+1):
val = ((math.factorial(numrows)) / ((math.factorial(count)) * math.factorial(numrows - count)))
nextrow.append(int(val))
count += 1

numrows += 1
numcols += 1
print(nextrow)

return nextrow
list = [1]
print(list)
for x in range(5):
list = pascals_triangle(list)

你差一点就成功了。这应该可以工作,设置"列表"变量转换为函数返回的输出。

注意:"list"是一个默认函数,不应该真的被覆盖。我建议使用另一个变量名,以免在后面引起任何令人困惑的错误。

最新更新