How to combine a number list and a string list into a new list in python using recursion?
Question:
I want to combine a number list and a string list
Example a = [1, 2, 3], b = [a, b, c, d]
combine a and b
and the answer should be [1, a, 2, b, 3, c, d]
or a = [1,2,3], b = [b, d]
combine a and b
and the answer should be [1, b, 2, d, 3]
Here is my code
def combine(a, b):
a = [str(int) for int in a]
b = [str(int) for int in b]
if a and b:
if a[0] > b[0]:
a, b = b, a
return [a[0]] + combine(a[1:], b)
return a + b
a = [1, 2, 3]
b = [‘a’, ‘b’, ‘c’, ‘d’]
combine(a, b)
but my result is this
[‘1’, ‘2’, ‘3’, ‘a’, ‘b’, ‘c’, ‘d’]
Answers:
from itertools import zip_longest
a = [1, 2, 3]
b = ["a", "b", "c", "d"]
def merge_lists(a, b):
result = []
for a_, b_ in zip_longest(a, b):
if a_ is not None:
result.append(a_)
if b_ is not None:
result.append(b_)
return result
result = merge_lists(a, b)
With recursion
a = [1, 2, 3]
b = ["a", "b", "c", "d"]
result = []
i = 0
def merge_lists(a, b):
global i
if i < len(a):
result.append(a[i])
if i < len(b):
result.append(b[i])
i+=1
if i < len(b) or i < len(a):
merge_lists(a, b)
merge_lists(a, b)
I want to combine a number list and a string list
Example a = [1, 2, 3], b = [a, b, c, d]
combine a and b
and the answer should be [1, a, 2, b, 3, c, d]
or a = [1,2,3], b = [b, d]
combine a and b
and the answer should be [1, b, 2, d, 3]
Here is my code
def combine(a, b):
a = [str(int) for int in a]
b = [str(int) for int in b]
if a and b:
if a[0] > b[0]:
a, b = b, a
return [a[0]] + combine(a[1:], b)
return a + b
a = [1, 2, 3]
b = [‘a’, ‘b’, ‘c’, ‘d’]
combine(a, b)
but my result is this
[‘1’, ‘2’, ‘3’, ‘a’, ‘b’, ‘c’, ‘d’]
from itertools import zip_longest
a = [1, 2, 3]
b = ["a", "b", "c", "d"]
def merge_lists(a, b):
result = []
for a_, b_ in zip_longest(a, b):
if a_ is not None:
result.append(a_)
if b_ is not None:
result.append(b_)
return result
result = merge_lists(a, b)
With recursion
a = [1, 2, 3]
b = ["a", "b", "c", "d"]
result = []
i = 0
def merge_lists(a, b):
global i
if i < len(a):
result.append(a[i])
if i < len(b):
result.append(b[i])
i+=1
if i < len(b) or i < len(a):
merge_lists(a, b)
merge_lists(a, b)