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

后端 未结 4 639
予麋鹿
予麋鹿 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 01:03

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

    Your test case:

    In [2]: a = [1,2,3,4]
    
    In [3]: b = [5,6,7,8]
    
    In [4]: combine(a,b)
    Out[4]: [1, 2, 3, 4, 5, 6, 7, 8]
    

    Another test case:

    In [24]: a
    Out[24]: [1, 2, 3, 8, 9]
    
    In [25]: b
    Out[25]: [1, 3, 5, 6, 7]
    
    In [26]: combine(a,b)
    Out[26]: [1, 1, 2, 3, 3, 5, 6, 7, 8, 9]
    

提交回复
热议问题