How to define a recursive function to merge two sorted lists and return a new list with a increasing order in Python?

后端 未结 4 635
予麋鹿
予麋鹿 2021-01-27 00:32

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

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 00:40

    Just a simpler version:

    def combine(a, b):
        if a and b:
            if a[0] > b[0]:
                a, b = b, a
            return [a[0]] + combine(a[1:], b)
        return a + b
    

    Test:

    >>> combine([1,3,6,8], [2,4,5,7])
    [1, 2, 3, 4, 5, 6, 7, 8]
    

提交回复
热议问题