Reputation: 91
I am currently trying to code a function recursively but I am stuck on the base case. Basically, my problem is that I don't know how to create the base case since I don't know how to check every element of the list recursively. If I was to use a for loop, it would go something like
for i in range(len(A)):
where A
is a list. How would I changed that into recursion?
Edit: I am now aware that I gave too little details. Lets say I have a list of numbers [5,6,-1,7,-3]
I want my output to be just the positive numbers, so by the code it would be [5,6,3]
. Now my problem is that I can easily do this using a for
loop to check every element of the list, but I want to do it recursively and I don't know how to do that for lists. I hope It is clearer now/makes sense.
Upvotes: 0
Views: 1605
Reputation: 123491
This seems to work. The base case is when there are no more numbers left to check.
def positive_vals(nums, result=None):
if result is None:
result = []
if not nums:
return result
else:
if nums[0] > 0:
result.append(nums[0])
return positive_vals(nums[1:], result)
numbers = [5, 6, -1, 7, -3]
print(positive_vals(numbers)) # -> [5, 6, 7]
Upvotes: 0
Reputation: 1757
The base case is when then list element is not a nested list, like follows:
def visit_list_rec(x):
# base case, we found a non-list element
if type(x) != list:
print(x)
return
# recursive step, visit each child
for element in x:
visit_list_rec(element)
if __name__ == "__main__":
visit_list_rec(["this", "is", ["a", ["nested", "list"]]])
Upvotes: 1