如何使递归排序列表函数工作?

2024-05-19 11:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个列表排序算法,而不使用Python的sorted。到目前为止我有:

def order(lst):
    if lst == [] or len(lst) == 1:
        return lst
    elif lst[0] < order(lst[1:])[0] or lst[0] == order(lst[1:])[0]:
        return [lst[0]] + order(lst[1:])
    return order(lst[1:]) + [lst[0]]

但是,它在处理具有重复条目的列表时有困难。我假设这是因为程序可以根据某个事物的大小不断扩展列表,如果它运行到某个具有相同值的事物,它就会中断进程。然而,我不知道如何解决它在所有,所以有没有更好的方法来做到这一点,还是我必须使用一个不同的方式(使用分钟是我在这一点上的最佳选择)?如有任何提示,将不胜感激。你知道吗


Tags: or程序目的算法列表lenreturnif
1条回答
网友
1楼 · 发布于 2024-05-19 11:02:44
def order(lst):
    count = 0 #this is the count of how many times we've seen a repeated digit
    def helper(lst):
        nonlocal count
        if len(lst) <= 1:
            return lst
        lst_without_min = []
        for x in lst:
            if count < 1 and x == min(lst): #okay, we've already seen the minimum digit once, if it's repeated again keep it in there
                count += 1
            else:
                lst_without_min.append(x)
        return [min(lst)] + order(lst_without_min)
    return helper(lst)

这里有一个有效的解决方案,它确实很长,而且可能效率很低,但它是有效的。你知道吗

相关问题 更多 >

    热门问题