I want to define a recursive function to merge two sorted lists (these two lists are sorted) and return a new list containing all the values in both argument lists with a incre
Here are some alternatives:
The smarter way to do this is to use merge function from the heapq module:
from heapq import merge
list(merge(a,b))
Test:
>>> a = [1,2,3,4,7,9]
>>> b = [5,6,7,8,12]
>>> [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 12]
And without using recursion:
def combine(a:list, b:list):
alist = []
i,j = 0,0
while i < len(a) and j < len(b):
if a[i] < b[j]:
alist.append(a[i])
i+=1
else:
alist.append(b[j])
j+=1
while i < len(a):
alist.append(a[i])
i+=1
while j < len(b):
alist.append(b[j])
j+=1
return alist
Test:
>>> a = [1,2,3,4,7,9]
>>> b = [5,6,7,8,12]
>>> [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 12]