Using Python, I want to print only positive integers on the list through recursion

Question:

I’m studying recursion now, and my head is about to explode trying to use it.

If lst = [-1, -4, 0, 3, 6], my expecting output is result = [3, 6].

I tried this,

def positive(lst):
    result = []
    if not lst:
        return result
    else:
        if lst[0] > 0:
            result.append(lst[0])
        return positive(lst[1:])

But output is empty list. like result = [ ].

Asked By: lililllil

||

Answers:

You are not passing your cache down through recursion

def positive(lst, result):
    if not lst:
        return result
    else:
        if lst[0] > 0:
            result.append(lst[0])
        return positive(lst[1:], result)


lst_in = [-1, -4, 0, 3, 6]
result = []
res = positive(lst_in, result)
print(res)

In your version, result’s scope was limited to a single function execution. You need to have a common cache(in your case result list). You can do that by passing it down to each function, or defining it in global scope

Answered By: drx

In your recursive part, positve() always return a further call to itself. Therefore, you always get the result of the final call to positive(), i.e., an empty list.

A solution that does not change your interface is as below, but at the cost of moving list every time.

def positive(lst):
    result = []
    if lst:
        if lst[0] > 0:
            result.append(lst[0])
        result.extend(positive(lst[1:]))
    return result

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

Edit: Because we add at most one value each time, we can use insert instead of extend to update result with lower cost.

def positive2(lst):
    if not lst:
        return []
    result = positive2(lst[1:])
    if lst[0] > 0:
            result.insert(0, lst[0])
    return result
Answered By: ILS
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.