2015-10-08 37 views
1
def insert3(x,ss): 
    left = [] #why this need to add properly by list, or not it just return the recent result. 
    while ss!= []: 
     for y in ss: 
      if x<= ss[0]: 
       return left + [x] + ss[0:] 
      else: 
       ss, left = ss[1:], left + [ss[0]] 
     return left + ss + [x] 

print(insert3(6,[2,4,5,7,8])) 

這是循環for函數的正確用法嗎?在列表中使用for循環對數字進行排序

我改變了一點。它是否正確?

def insert3(x,ss): 
    left = [] 
    for y in ss: 
     if x<= ss[0]: 
      return left + [x] + ss[0:] 
     else: 
      ss, left = ss[1:], left + [ss[0]] 
    return left + ss + [x] 

print(insert3(6,[2,4,5,7,8])) 
+2

你是什麼意思*「正確」*?它工作嗎? – jonrsharpe

+0

它確實有效,但它說y是未使用的變量。 –

+1

好吧,看看你的代碼 - 你有沒有使用*'y'? – jonrsharpe

回答

1

爲什麼要編寫複雜的代碼插入到排序列表中?您可以使用類似的東西:

>>> x = [2,4,5,7,8] 
>>> x.append(6) 
>>> x.sort() 
>>> x 
[2, 4, 5, 6, 7, 8] 

除非您遇到巨大的性能瓶頸,否則最好使用該語言的功能。我喜歡將此優化稱爲開發工作。

+0

這是我的班級任務,所以不得不。 –

0

從這個question使用二等分將是一個很好的方法來解決這個問題。另見wikipedia。但一個簡單的例子,你想要做的是:

def Insert(val, list): 
    for i, entry in enumerate(list): 
     if val < entry: 
      return list[0:i] + [val] + list[i:] 
print(Insert(6,[2,4,5,7,8])); 
相關問題