You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python递归筛选列表正整数返回空列表的问题求助

Why Your Recursive Function Returns an Empty List

Let's break down the issue with your current code. The problem lies in how you're handling the result list across recursive calls:

  • Each call initializes a new empty result: Every time you run positive(lst), you create a fresh empty list. When you append a positive element to this list, you don't combine it with the result from processing the rest of the list.
  • You discard the current result: Instead of returning the result you built (with the positive element) plus the output of positive(lst[1:]), you just return positive(lst[1:]) directly. This means all the positive elements you collected in earlier calls are lost—only the base case's empty list propagates back up.

Correct Recursive Implementation

Here's a fixed version that properly accumulates positive elements through recursion:

def positive(lst):
    # Base case: empty list returns empty list
    if not lst:
        return []
    # If first element is positive, include it and recurse on the rest
    elif lst[0] > 0:
        return [lst[0]] + positive(lst[1:])
    # If not positive, just recurse on the rest of the list
    else:
        return positive(lst[1:])

# Test it out
lst = [-1, -4, 0, 3, 6]
result = positive(lst)
print(result)  # Output: [3, 6]

How This Works:

  • Base Case: When the input list is empty (not lst), we return an empty list—this stops the recursion.
  • Positive Element: If the first element is greater than 0, we create a list containing that element and concatenate it with the result of processing the remaining elements (lst[1:]).
  • Non-Positive Element: If the first element isn't positive, we skip it and just return the result of processing the rest of the list.

Let's walk through your test case step-by-step:

  1. positive([-1, -4, 0, 3, 6]) → -1 isn't positive, so return positive([-4, 0, 3, 6])
  2. positive([-4, 0, 3, 6]) → -4 isn't positive, return positive([0, 3, 6])
  3. positive([0, 3, 6]) → 0 isn't positive, return positive([3, 6])
  4. positive([3, 6]) → 3 is positive, return [3] + positive([6])
  5. positive([6]) → 6 is positive, return [6] + positive([])
  6. positive([]) → return []
  7. Putting it all together: [6] + [] = [6], then [3] + [6] = [3,6], which propagates back up as the final result.

Alternative Version (Using Accumulator)

If you prefer using an accumulator to build the result (which can be more efficient for large lists), you can modify the function to take an optional accumulator parameter:

def positive(lst, acc=None):
    if acc is None:
        acc = []
    if not lst:
        return acc
    if lst[0] > 0:
        acc.append(lst[0])
    return positive(lst[1:], acc)

# Test
lst = [-1, -4, 0, 3, 6]
print(positive(lst))  # Output: [3,6]

This version uses an accumulator list that's passed through recursive calls, appending positive elements as we go. The base case returns the fully built accumulator.

内容的提问来源于stack exchange,提问作者lililllil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:22:45