-3

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']

joule.v
  • 5
  • 2
  • Welcome to Stack Overflow! Please take the [tour]. If this is homework, please read [How to ask and answer homework questions](https://meta.stackoverflow.com/q/334822/4518341). What have you already tried, and where are you stuck? See also [ask]. Just in case this isn't homework, why do you want to use recursion? – wjandrea Sep 18 '22 at 23:45

1 Answers1

-2
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)
Eftal Gezer
  • 191
  • 1
  • 8