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 []
andif not A
to test for empty listuse
A[:1]
to get a list of one element instead ofA[0]
which is anint
([A[0]]
does same)simplified a bit the
else
, you don’t need them if the previous branches doesreturn
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
isTrue
, thenint(True) == 1
so your sliceA[:1]
if
A[0]>0
isFalse
, thenint(False) == 0
so your sliceA[: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 []