Skip to content
Advertisement

How do I append things on list through recursion?

I have this code:

def positive(A):
    if len(A)==0:
        return 0
    else:
        if A[0]>0:
            return A [0]+positive(A[1:])
        else:
            return positive(A[1:])

Theoretically, when I input a list of numbers, it will return the list of positive numbers. For example, when I pass [2,5,-3,-5,2,-6] it will return [2,5,2]. But in my code, what happens is that the positive values are evaluated so this returns 9. I think my problem is that in A [0]+positive(A[1:]) line but I don’t know how to change it. Any help is appreciated.

Advertisement

Answer

Your code should return a list for every case,

  • so for the empty list case do return [] and if not A to test for empty list

  • use A[:1] to get a list of one element instead of A[0] which is an int ( [A[0]] does same)

  • simplified a bit the else, you don’t need them if the previous branches does return

def positive(A):
    if not A:
        return []
    if A[0] > 0:
        return A[:1] + positive(A[1:])
    return positive(A[1:])

A nice idea from the comments is to use the boolean condition directly as the index to slice with

  • if A[0]>0 is True, then int(True) == 1 so your slice A[:1]

  • if A[0]>0 is False, then int(False) == 0 so your slice A[:0] which is empty

def positive(A):
    if not A:
        return []
    return A[:int(A[0] > 0)] + positive(A[1:])

With inline if

def positive(A):
    return A[:int(A[0] > 0)] + positive(A[1:]) if A else []
10 People found this is helpful
Advertisement