2010-12-03 140 views
0

在即將到來的問題中有一個遞歸選擇排序需要完成。遞歸選擇排序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" 

我知道如何使用關鍵→ l.sort(key=str.lower)得到這個。但是這個問題想要我提取最大元素,而不是最小值,只能將其提交給遞歸排序的子列表。

如果我能得到任何幫助,我將不勝感激。

+0

請注意,您可以通過將行縮進四個空格來將行格式化爲代碼。編輯器工具欄中的「101 \ n010」按鈕可以爲您做到這一點。您可以使用底部的編輯鏈接編輯您的問題,並現在格式化示例代碼。單擊編輯器工具欄中的橙色問號以獲取更多信息和格式化提示。 – outis 2010-12-03 02:55:43

回答

0

排序方法應該做你想做的。如果你想相反,只需使用list.reverse()

如果你的工作是做出自己的排序方法,那可以做到。

也許嘗試這樣的:

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 
2

所以。你明白這個問題嗎?

讓我們來看看你被要求做什麼:

上提取的最大元素,而不是最低,只有.append(...)到一個遞歸排序子表。

所以,我們做以下事情:

1)提取的最大元素。你明白「提取物」在這裏的含義嗎?你知道如何找到最大元素?

2)對子列表進行遞歸排序。這裏,「子列表」由我們提取最大元素後的所有其他部分組成。你知道遞歸如何工作嗎?您只需再次使用子列表調用您的排序函數,依靠它來進行排序。畢竟,你的函數的目的是對列表進行排序,所以這應該是可行的,對吧? :)

3).append()將最大元素放到排序子列表的結果上。這不應該要求任何解釋。

當然,我們需要遞歸的基本情況。我們什麼時候有基本情況?當我們不能按照書面的步驟完成步驟時。這是什麼時候發生的?那麼,爲什麼會發生?答案:如果沒有元素,我們不能提取最大元素,因爲那時沒有最大元素要提取。

因此,在函數的開頭,我們檢查是否傳遞了一個空列表。如果我們是,我們只是返回一個空列表,因爲排序一個空列表會導致一個空列表。 (你明白爲什麼?)否則,我們會經歷其他步驟。