Reputation: 131
I'm trying to write a function that takes 2 parameters, an int and a list. I have to compare each element in the list with the int and store them in a tuple consisting of 2 lists, a list with numbers greater than and a list with numbers less than. I'm trying to do this recursively, but I don't know how to store the values so that they are not erased when I use recursion.
def greater_less(v:int,l:list):
if l == []:
return ([],[])
elif l[0] > v:
more = [l[0]]
return more + greater_less(v,l[1:])
elif l[0] < v:
less = [l[0]]
return less + greater_less(v,l[1:])
problem is...when l == []
, everything is cleared. Also when I call my function recursively, I believe everything before is also cleared
practicing recursion so a hint as to how to fix my issue with recursion would be great
Upvotes: 1
Views: 565
Reputation: 81926
Let's write some code:
def greater_less(v, l):
# First, are we in the base case?
if not l:
return [], []
# Second, do the recursive step
smaller, greater = greater_less(v, l[1:])
# Now, we also have l[0] to insert into these lists.
if l[0] < v:
smaller.insert(0, l[0])
elif l[0] > v:
greater.insert(0, l[0])
else:
pass
# Finally, return these lists
return smaller, greater
Note that we store the returned lists from the recursive call, prepend to the correct one, and then return them.
Let's look at a run of this code. To make this a bit less repetitive, I'm going to labels the 4 sections of code in the function A through D. So A would be the base case check (if not l...
) and C would be the if l[0] < v ... else: pass
code.
main() calls greater_less(2, [1,2,3])
A: We are not in the base case because l has 3 elements.
B: Recursive call of greater_less(2, [2, 3])
A: We are not in the base case because l has 2 elements.
B: Recursive call of greater_less(2, [3])
A: We are not in the base case because l has 1 element.
B: Recursive call of greater_less(2, [])
A: We __are__ in the base case because l has 0 elements.
Therefore, we won't reach B, C, or D of this call.
We return [], [].
B: Recursive call returns. We have smaller = [], greater = []
C: l[0] is 3 which is greater than 2.
Therefore, we prepend onto greater.
D: Return smaller = [], greater = [3]
B: Caller returns. We have smaller = [], greater = [3]
C: l[0] is 2, which is equal to 2.
So we don't prepend this number to either list.
D: return smaller = [], greater = [3]
B: Caller returns. We have smaller = [], greater = [3]
C: l[0] is 1, which is less than 2.
So prepend to the smaller list.
D: Return smaller = [1], greater = [3]
main's call to greater_less() now returns with ([1], [3])
Upvotes: 4