I am trying to learn recursion and am separating odd and even values in two lists and merging them to another list as below:
Code:
def separateNumbers(L):
evenList = []
oddList = []
main = []
if len(L)==0:
return L
if L[0] % 2 == 0:
evenList.append(L[0])
separateNumbers(L[1:])
if L[0] % 2 == 1:
oddList.append(L[0])
separateNumbers(L[1:])
main.append(evenList)
main.append(oddList)
return main
inputList = [1,2,3,4,5,6,7,8,9,10]
L = separateNumbers(inputList)
print(L)
Input:
L = [1,2,3,4,5,6]
Output:
[[1,3,5], [2,4,6]]
The even and odd arrays reset everytime the recursive function is called, how can I fix this?
Tried with inner function:
def separateNumbers(L):
evenList = []
oddList = []
main = []
def inner(L):
if len(L)==0:
return L
if L[0] % 2 == 0:
evenList.append(L[0])
inner(L[1:])
if L[0] % 2 == 1:
oddList.append(L[0])
inner(L[1:])
main.append(evenList)
main.append(oddList)
return main
a = inner(L)
return a
Output:
[[2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8,
10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
CodePudding user response:
You don't need a nested function. try:
def separate_numbers(lst):
if not lst: # empty list
return [], []
odd, even = separate_numbers(lst[1:]) # recursion call
if lst[0] % 2: # if the first item is odd
return [lst[0], *odd], even
else: # if even
return odd, [lst[0], *even]
lst = [1,2,3,4,5,6,7,8,9,10]
print(separate_numbers(lst)) # ([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
The function calls itself using the tail part of the input list, receiving two lists: odd
for odd numbers and even
for even numbers. Then it returns those lists, after attaching the head element lst[0]
to one of the lists.