2014-09-13 58 views
1

我在Python中有一個家庭作業任務,並遇到了腦凍結。所以我應該使用插入排序來做O(n2)練習。 例如,我有兩個列表[]和[5,8,1,1],程序應該從一個列表中插入值到另一個列表,方法是先從第一個列表中刪除,然後按正確順序刪除另一列表中的列表: [] [5,8, 1,1] = [5] [8,1,1] = [5,8] [1,1] = [1,5,8] [1] = [1,1,5,8] []在Python中插入排序

我想出了一些東西,不知道我是否在正確的軌道上,但這似乎是最合理的。縮進是爲了順序,但在這裏複製代碼莫名其妙地搞砸了。 對不起愛沙尼亞語,愛沙尼亞語是強制性的。

def pisteMeetod2(t2ishulk): 
    tulemus = [] #new list 
    hulgacopy = t2ishulk[0:len(t2ishulk)] #main list 
    for el in t2ishulk: #going through first list 
     if not tulemus: #if list empty (which it at the beginning is) then from here 
      tulemus.append(el) 
      del hulgacopy[0] 
     else: 
      for elemendid in tulemus: #check if there is a lower element from new list 
       n = 0 
       if hulgacopy[0] <= tulemus[n]: 
        tulemus.insert(n-1,el) 
        del hulgacopy[0] 
        break 
       n = n + 1 

所以,現在我遇到了麻煩,第二次循環會怎麼樣。完成檢查結果列表中名爲「tulemus」的元素之後,如果它沒有找到任何匹配,我應該如何繼續我的代碼,以便將「el」添加到tulemus中。

回答

3

您可以添加else子句內for循環:如果循環沒有使用break終止

for elemendid in tulemus: #check if there is a lower element from new list 
    n = 0 
    if hulgacopy[0] <= tulemus[n]: 
     tulemus.insert(n, el) 
     del hulgacopy[0] 
     break 
    n = n + 1 
else: 
    tulemus.append(el) 
    del hulgacopy[0] 

它的身體被執行。您可以在Python的official tutorial中閱讀關於循環中else子句的更多信息。

請注意,如果您在迭代過程中發現插入點,則應該使用tulemus.insert(n, el)而不是tulemus.insert(n-1, el)將當前元素插入到那裏。否則,當n == 0時,您將最終插入列表末尾(索引-1)。

+0

謝謝,得到它的工作:) – charen 2014-09-13 16:59:40