递归选择排序python

2024-05-16 12:09:40 发布

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

在即将到来的问题中有一个递归的选择排序。在

def selsort(l):
    """
    sorts l in-place.
    PRE: l is a list.
    POST: l is a sorted list with the same elements; no return value.
    """                    

l1 = list("sloppy joe's hamburger place")
vl1 = l1

print l1    # should be: """['s', 'l', 'o', 'p', 'p', 'y', ' ', 'j', 'o', 'e', "'", 's', ' ', 'h', 'a', 'm', 'b', 'u', 'r', 'g', 'e', 'r', ' ', 'p', 'l', 'a', 'c', 'e']"""

ret = selsort(l1)

print l1    # should be """[' ', ' ', ' ', "'", 'a', 'a', 'b', 'c', 'e', 'e', 'e', 'g', 'h', 'j', 'l', 'l', 'm', 'o', 'o', 'p', 'p', 'p', 'r', 'r', 's', 's', 'u', 'y']"""
print vl1   # should be """[' ', ' ', ' ', "'", 'a', 'a', 'b', 'c', 'e', 'e', 'e', 'g', 'h', 'j', 'l', 'l', 'm', 'o', 'o', 'p', 'p', 'p', 'r', 'r', 's', 's', 'u', 'y']"""

print ret   # should be "None"

我知道如何通过使用键→{}来获得这个。但是这个问题需要我提取最大元素,而不是最小元素,只是为了.append(...)将其放到递归排序的子列表中。在

如果我能得到任何帮助,我将不胜感激。在


Tags: in元素l1排序isdefplacebe
2条回答

所以。你明白这个问题吗?在

让我们看看你被要求做什么:

extract the maximum element, instead of the minimum, only to .append(...) it on to a recursively sorted sublist.

所以,我们要做以下事情:

1)提取最大元素。你明白“摘录”是什么意思吗?你知道怎么找到最大元素吗?在

2)递归排序子列表。在这里,“子列表”由提取最大元素后的所有其他元素组成。你知道递归是怎么工作的吗?您只需使用子列表再次调用sort函数,依靠它来进行排序。毕竟,你的函数的目的是对列表进行排序,所以这应该是有效的,对吧?:)

3).append()子列表排序结果上的最大元素。这不需要任何解释。在

当然,我们需要递归的基本情况。我们什么时候有基本情况?当我们不能完全按照所写的步骤去做。什么时候发生的?为什么会发生这种事?答:如果没有元素,则无法提取最大元素,因为这样就没有要提取的最大元素。在

因此,在函数开始时,我们检查是否传递了一个空列表。如果是,则返回一个空列表,因为对空列表进行排序会导致空列表。(你明白为什么吗?)否则,我们将进行其他步骤。在

sort方法应该做你想做的。如果你想反过来,就用列表.反转()

如果你的工作是制定你自己的排序方法,这是可以做到的。在

也许可以试试这样的方法:

def sort(l):
    li=l[:]                                        #to make new copy
    newlist = []                                   #sorted list will be stored here
    while len(li) != 0:                            #while there is stuff to be sorted
        bestindex = -1                             #the index of the highest element
        bestchar = -1                              #the ord value of the highest character
        bestcharrep = -1                           #a string representation of the best character
        i = 0
        for v in li:
            if ord(v) < bestchar or bestchar == -1:#check if string is lower than old best
                bestindex = i                      #Update best records
                bestchar = ord(v)
                bestcharrep = v
            i += 1
        del li[bestindex]                          #delete retrieved element from list
        newlist.append(bestcharrep)                #add element to new list
    return newlist                                 #return the sorted list

相关问题 更多 >