【问题标题】:Coding convention for nested functions嵌套函数的编码约定
【发布时间】: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 的暴力递归解决方案)。

请注意,profitsweights 在嵌套函数中的任何时候都不会发生变化,但它们仍然会传递给每个递归调用。这是我经常看到的一种模式,对于不允许嵌套函数的语言来说很有意义,因此函数所需的所有内容都必须作为参数传入。

不过,对于 Python,函数 knapsack_recursive 可以访问 solve_knapsack 的参数,因此我们可以从前者的形式参数中删除 profitsweights,代码就可以正常工作了.

是否有理由选择其中之一?

【问题讨论】:

    标签: python python-3.x function nested-function


    【解决方案1】:

    正如之前的海报所示,您没有包含嵌套函数。我认为您打算将 knapsack_recursive 用作嵌套函数,并且想知道是否将 profitsweights 作为参数传递。

    这是一个判断问题。如果这是我的代码,我不会将它们作为参数传递,特别是因为这些在整个计算过程中都没有改变。但这里没有对错之分。

    【讨论】:

    • 你希望 knapsack_recursive 成为一个嵌套函数” - 是的,现在固定缩进。
    【解决方案2】:

    您发布的代码不包含任何嵌套函数。 如果不将参数传递给“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

    【讨论】:

    • 我认为发帖者的意图是让 knapsack_recursive 成为一个嵌套函数。
    • 已修复!使用缩进表示范围的语言并不少见。现在您可以回答提出的问题了。
    猜你喜欢
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多