【问题标题】:How do you count the number of negative items in a list using a recursive function?如何使用递归函数计算列表中负项的数量?
【发布时间】:2022-12-03 01:56:53
【问题描述】:

我必须创建一个递归函数来计算给定列表中有多少负值,但我无法弄清楚每个条件应该返回什么。

def countNegatives(list):
    """Takes in a list of numbers and
    returns the number of negative numbers
    that are inside the list."""
    count = 0
    if len(list) == 0:
        return 0
    else:
        if list[0] < 0:
            return count + 1
        else:
            return countNegatives(list[1:])

print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1

【问题讨论】:

  • 如何使用固定列表添加对函数的调用,以便我们可以看到所需的和实际的输出。这有助于做出有效的答案。
  • 想一想,你的代码只能返回0或1,没有别的。

标签: python recursion


【解决方案1】:

您的代码的问题在于您没有跟踪递归调用中负数的运行计数。具体来说,当列表的第一项为负数时,您将返回 count + 1,并丢弃列表的其余部分,而不是使用递归调用来计算列表其余部分中负数项的数量。

要解决此问题,您可以在两种情况下将递归调用的结果添加到 count,当第一项为负数和第一项为负数时。这样,负项的运行计数将通过递归调用累加,并在达到基本情况时作为最终结果返回。

这是您的代码的更正版本:

def countNegatives(lst):
    """Takes in a list of numbers and
    returns the number of negative numbers
    that are inside the list."""
    count = 0
    if len(lst) == 0:
        return 0
    else:
        if lst[0] < 0:
            count += 1
        count += countNegatives(lst[1:])
        return count

print(countNegatives([0, 1, -1, 3, -5, 6]))  # Output: 2
print(countNegatives([-1, -3, 50, -4, -5, 1]))  # Output: 4

请注意,我将参数list重命名为lst,因为list是Python内置数据类型的名称,最好避免使用内置名称作为变量名。

【讨论】:

    【解决方案2】:

    list[0] &lt; 0 时,您的代码会忽略列表的其余部分,但可能会有更多的负值需要计算。

    所以在那种情况下不要这样做:

            return count + 1
    

    但:

            return 1 + countNegatives(list[1:])
    

    【讨论】:

      【解决方案3】:

      您缺少的步骤是将计数添加到递归调用的返回值,以便所有递归调用的返回值在最后汇总。这是您可以执行此操作的一种方法:

      def countNegatives(list):
          #if the list length is zero, we are done
          if len(list) == 0:
              return 0
      
          # Get the count of this iteration
          count = 1 if list[0] < 0 else 0
          # sum the count of this iteration with the count of all subsequent iterations
          return count + countNegatives(list[1:])
      

      因此,对于您的第一个示例,您的代码执行的实际步骤如下所示:

      return 0 + countNegatives([1, -1, 3, -5, 6])
      return 0 + countNegatives([-1, 3, -5, 6])
      return 1 + countNegatives([3, -5, 6])
      return 0 + countNegatives([-5, 6])
      return 1 + countNegatives([6])
      return 0 + countNegatives([])
      return 0
      

      展开所有值给出:

      return 0 + 0 + 1 + 0 + 1 + 0 + 0 
      

      【讨论】:

        猜你喜欢
        • 2013-03-19
        • 1970-01-01
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-09
        • 2021-02-24
        • 1970-01-01
        相关资源
        最近更新 更多