Python 如何修复排序函数

Python 如何修复排序函数,python,recursion,Python,Recursion,我需要编写一个名为sort的递归函数;它被传递给任何无序列表(all int或all str),并返回一个新列表,其中包含参数列表中的每个值,但按排序/非降序排列。但是我不能调用任何Python的函数/方法来执行排序 另外,对于任何至少有2个值的列表,我必须将列表一分为二并递归调用sort来对每个较小的列表进行排序,我必须使用上面写的merge函数来合并从这些递归调用返回的这两个排序列表 merge是一个将两个列表合并并排序的函数 def merge (l1,l2): if l1 and

我需要编写一个名为sort的递归函数;它被传递给任何无序列表(all int或all str),并返回一个新列表,其中包含参数列表中的每个值,但按排序/非降序排列。但是我不能调用任何Python的函数/方法来执行排序

另外,对于任何至少有2个值的列表,我必须将列表一分为二并递归调用sort来对每个较小的列表进行排序,我必须使用上面写的merge函数来合并从这些递归调用返回的这两个排序列表

merge是一个将两个列表合并并排序的函数

def merge (l1,l2):
    if l1 and l2:
        if l1 == [] and l2 == []:
            return []
        if l1[0] > l2[0]:
            l1, l2 = l2, l1 
        return [l1[0]] + merge(l1[1:], l2)
    return l1 + l2


def sort(l):
    x = len(l) / 2
    x = int(x)
    y = merge(l[0:x], l[x+1:])
    return y
例如,调用sort([4,5,3,1,6,7,2])将递归调用列表[4,5,3]和[1,6,7,2])上的sort,分别返回列表[3,4,5]和[1,2,6,7],合并后将返回列表[1,2,3,4,5,6,7]

我的函数出现以下错误

merge([1,3,5,8,12],[2,3,6,7,10,15]) returns [1,2,3,3,5,6,7,8,10,12,15].

我的排序方法有什么问题?有人能帮我修一下吗?提前谢谢

好的,基本上你所做的一切都是多余的

39 *Error: sort([1,2,3,4,5,6,7]) -> [1, 2, 3, 5, 6, 7] but should -> [1, 2, 3, 4, 5, 6, 7]
40 *Error: sort([7,6,5,4,3,2,1]) -> [3, 2, 1, 7, 6, 5] but should -> [1, 2, 3, 4, 5, 6, 7]
41 *Error: sort([4,5,3,1,2,7,6]) -> [2, 4, 5, 3, 7, 6] but should -> [1, 2, 3, 4, 5, 6, 7]
42 *Error: sort([1,7,2,6,3,5,4]) -> [1, 3, 5, 4, 7, 2] but should -> [1, 2, 3, 4, 5, 6, 7]
如果您有一个列表或元组的列表,并且希望按照每个列表或元组的索引进行排序,那么还有一点好处

list1 = [1,3,5,8,12]
list2 = [2,3,6,7,10,15]

list3 = list1 + list2 # Merges lists

list3_sorted = sorted(list3) # Sorts them

编辑:我现在意识到你不能使用任何内置函数,请给我一点时间,看看我是否能弄明白你需要的是合并排序,我相信互联网上有多个合并排序伪代码

无论如何,这是我在Python 3中的一个版本:

from operator import itemgetter

list = [(2,6), (3,4)]
list_sorted = sorted( list, key=itemgetter(1) ) # Will sort by index 1 of each item.
def合并排序(lst):
如果len(lst)<2:
返回lst
其他:
中间=len(lst)//2
#递归,宝贝
左半=合并排序(lst[:中间])
右半=合并排序(lst[中间:)
返回合并(左半,右半)
def合并(左、右):
结果=[]
i、 j=0,0
而i
三个问题:

  • 你的
    y=merge(l[0:x],l[x+1:])
    丢失
    l[x]
    ,使其
    y=merge(l[:x],l[x:])
  • 它不会对两半进行排序,所以将其设置为
    y=merge(sort(l[:x]),sort(l[x:])
  • 您没有基本情况,在无事可做时停止递归
稍加修改和简化:

def mergesort(lst):
    if len(lst) < 2:
        return lst
    else:
        middle = len(lst) // 2
        # recursion, baby
        left_half = mergesort(lst[:middle])
        right_half = mergesort(lst[middle:])
        return merge(left_half, right_half)

def merge(left, right):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        elif left[i] > right[j]:
            result.append(right[j])
            j += 1
    result += left[i:] + right[j:]
    return result
def排序(l):

如果len(l)“但我不能调用任何执行排序的Python函数/方法”您没有仔细阅读我的描述,我就不能调用任何执行排序的Python函数/方法。另外,我需要在排序函数中调用merge方法OK,很抱歉我没有读到。我会调查并更新我的答案。
def sort(l):
    if len(l) <= 1:
        return l
    x = len(l) // 2
    return merge(sort(l[:x]), sort(l[x:]))