问题描述
def solve_knapsack(profits,weights,capacity):
def knapsack_recursive(profits,capacity,currentIndex):
# base checks
if capacity <= 0 or currentIndex >= len(profits):
return 0
# recursive call after choosing the element at the currentIndex
# if the weight of the element at currentIndex exceeds the capacity,we shouldn't process this
profit1 = 0
if weights[currentIndex] <= capacity:
profit1 = profits[currentIndex] + knapsack_recursive(
profits,capacity - weights[currentIndex],currentIndex + 1)
# recursive call after excluding the element at the currentIndex
profit2 = knapsack_recursive(profits,currentIndex + 1)
return max(profit1,profit2)
return knapsack_recursive(profits,0)
(如果您很好奇,这是Knapsack problem的强力递归解决方案)。
请注意,profits
和weights
不会在嵌套函数中随时更改,但仍会传递给每个递归调用。这是我经常看到的一种模式,对于不允许嵌套函数的语言是有意义的,因此函数所需的所有内容都必须作为参数传递。
但是,对于Python而言,函数knapsack_recursive
可以访问solve_knapsack
的参数,因此我们可以从前者的形式参数中删除profits
和weights
,代码就可以正常工作。
有理由选择一个吗?
解决方法
如前一个海报所示,您没有包括嵌套函数。我认为您打算将knapsack_recursive
用作嵌套函数,并且想知道是否将profits
和weights
作为参数传递。
这是一个判断问题。如果这是我的代码,则不会将它们作为参数传递,尤其是因为在整个计算过程中这些参数都没有改变。但是这里没有对与错。
,您发布的代码不包含任何嵌套函数。 如果不将参数传递给“ knapsack_recursive”,它将无法正常工作。 函数不包含有关将在其内调用的范围的任何信息,因此如果您尝试使用在函数定义中不可访问的名称,则解释器将抛出NameError。您需要在“ solve_knapsack”中定义“ knapsack_recursive”,以便捕获传递给“ solve_knapsack”的参数。您可能需要阅读有关嵌套函数的更多信息,以进一步解释。例如此处:https://www.programiz.com/python-programming/closure#:~:text=A%20function%20defined%20inside%20another,in%20order%20to%20modify%20them。