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

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

    Instead of return, you should add it to the alist as like below.

    def combine(a, b):
        alist = []
        if a == [] and b == []:
           return alist
        if a != [] and b == []:
           return alist + a
        if a == [] and b != []:
           return alist + b
        if a != [] and b != []:
           if a[0] <= b[0]:
              alist.append(a[0])
              alist = alist +  combine(a[1:], b)
           if a[0] > b[0]:
              alist.append(b[0])
              alist = alist +  combine(a, b[1:])
        return alist
    

提交回复
热议问题