Skip to content
Advertisement

How do I append things on list through recursion?

I have this code:

JavaScript

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

JavaScript

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

JavaScript

With inline if

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement