2012-10-27 97 views
1

這不是基於效率,只需要非常非常基本的python知識(字符串,元組,列表基礎知識),因此不需要導入函數或使用排序/排序。 (這是使用Python 2.7.3)。Python:如何在沒有排序函數的情況下對列表中的字母進行排序?

比如我有一個列表:

unsort_list = ["B", "D", "A", "E", "C"] 
sort_list = [] 

sort_list需要能夠打印出:

"A, B, C, D, E" 

我可以用數字/整數做到這一點,是有字母類似的方法訂單字符串?如果不是,你會推薦什麼(即使效率不高),而無需導入或排序功能。

+2

http://en.wikipedia.org/wiki/Sorting_algorithm。選擇或泡泡最容易實現。 – georg

+1

這是你的功課,是你的功課! –

+1

如果你可以用數字來完成,你可以在字符串中做任何修改而不用修改代碼。在python中,你可以使用'<', '>'等比較字符串,就像數字一樣。 – Vikas

回答

1

這裏是用Python很短的實施Quicksort算法:

def quicksort(lst): 
    if not lst: 
     return [] 
    return (quicksort([x for x in lst[1:] if x < lst[0]]) 
      + [lst[0]] + 
      quicksort([x for x in lst[1:] if x >= lst[0]])) 

這是一個玩具的實現,很容易理解,但效率太低,在實踐中非常有用。它的目的更多是作爲一種學術活動來展示如何用功能性編程風格簡潔地編寫排序問題的解決方案。它將爲comparable對象列表中的問題的工作,特別是對於例如:

unsort_list = ['B', 'D', 'A', 'E', 'C'] 
sort_list = quicksort(unsort_list) 

sort_list 
> ['A', 'B', 'C', 'D', 'E'] 
+1

filter + lambda?不知道我喜歡這個。 – georg

+0

@ thg435好的,我也沒有。我改變它以使用解析 –

0

更簡單:

dc = { } 
for a in unsorted_list: 
    dc[a] = '1' 

sorted_list = dc.keys() 
+3

不,這是行不通的。 – georg

+0

這隻適用於'int',因爲在這種情況下,散列本身就是'int' –

1

只是爲了好玩:

from random import shuffle 
unsorted_list = ["B", "D", "A", "E", "C"] 

def is_sorted(iterable): 
    for a1,a2 in zip(iterable, iterable[1:]): 
    if a1 > a2: return False 
    return True 

sorted_list = unsorted_list 
while True: 
    shuffle(sorted_list) 
    if is_sorted(sorted_list): break 

平均複雜性應是階乘,最壞的情況是無限的

1
u = ["B", "D", "A", "E", "C"] 
y=[] 
count=65 
while len(y)<len(u): 
    for i in u: 
     if ord(i)==count: 
      y.append(i) 
      count+=1 
print(y) 
0

這僅使用min()內置和list對象的方法:

unsort_list = ["B", "D", "A", "E", "C"] 
sort_list = [] 

while unsort_list: 
    smallest = min(unsort_list) 
    sort_list.append(smallest) 
    unsort_list.pop(unsort_list.index(smallest)) 

print sort_list 

它破壞了未排序,所以你可能要做出的一個副本,並使用它。

0

list_val = [ 'C', 'd', 'E', 'A', 'R']

for passnum in range(len(list_val)-1, 0, -1): 
    for i in range(passnum): 
    if list_val[i] > list_val[i+1]: 
     list_val[i], list_val[i+1] = list_val[i+1], list_val[i] 

打印list_val

0

more_itertools庫具有一個合併算法的實現稱爲collate

import more_itertools as mit 

iterables = ["B", "D", "A", "E", "C"] 
list(mit.collate(*iterables)) 
# ['A', 'B', 'C', 'D', 'E'] 
相關問題