【发布时间】:2021-01-06 12:03:23
【问题描述】:
由于 Python 允许嵌套函数,我们可以编写如下代码:
def solve_knapsack(profits, weights, capacity):
def knapsack_recursive(profits, weights, 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, weights, capacity - weights[currentIndex], currentIndex + 1)
# recursive call after excluding the element at the currentIndex
profit2 = knapsack_recursive(profits, weights, capacity, currentIndex + 1)
return max(profit1, profit2)
return knapsack_recursive(profits, weights, capacity, 0)
(如果您好奇,这是Knapsack problem 的暴力递归解决方案)。
请注意,profits 和 weights 在嵌套函数中的任何时候都不会发生变化,但它们仍然会传递给每个递归调用。这是我经常看到的一种模式,对于不允许嵌套函数的语言来说很有意义,因此函数所需的所有内容都必须作为参数传入。
不过,对于 Python,函数 knapsack_recursive 可以访问 solve_knapsack 的参数,因此我们可以从前者的形式参数中删除 profits 和 weights,代码就可以正常工作了.
是否有理由选择其中之一?
【问题讨论】:
标签: python python-3.x function nested-function