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

后端 未结 4 670
予麋鹿
予麋鹿 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:43

    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]
    

提交回复
热议问题