Python: How to sort the alphabet in a list without sorted functions?

有些话、适合烂在心里 提交于 2019-12-11 04:38:16

问题


This is not based on efficiency, and has to be done with only a very very basic knowledge of python (Strings, Tuples, Lists basics) so no importing functions or using sort/sorted. (This is using Python 2.7.3).

For example I have a list:

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

sort_list needs to be able to print out:

"A, B, C, D, E"

I can do it with numbers/integers, is there a similar method for alphabetical order strings? if not what would you recommend (even if it isn't efficient.) without importing or sort functions.


回答1:


Here's a very short implementation of the Quicksort algorithm in Python:

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]]))

It's a toy implementation, easy to understand but too inefficient to be useful in practice. It's intended more as an academic exercise to show how a solution to the problem of sorting can be written concisely in a functional programming style. It will work for lists of comparable objects, in particular for the example in the question:

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

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



回答2:


just for fun:

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

the average complexity should be factorial and the worst case infinite




回答3:


even simpler:

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

sorted_list = dc.keys()



回答4:


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)



回答5:


This uses only the min() built-in and list object methods:

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

It destroys the unsorted list, so you might want to make a copy of it and use that.




回答6:


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]

print list_val




回答7:


The more_itertools library has an implementation of a mergesort algorithm called collate.

import more_itertools as mit

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



回答8:


Python already know which string is first and which is next depending on their ASCII values

for example:

"A"<"B"
 True

so we can write a simple bubble sort algorithm to sort the list of strings

unsort_list = ["B", "D", "A", "E", "C"]
def sortalfa(unsort_list):
    for i in range(len(unsort_list)-1):
        for j in range(i+1,len(unsort_list)):
            if unsort_list[i]>unsort_list[j]:
                temp = unsort_list[i]
                unsort_list[i] = unsort_list[j]
                unsort_list[j] = temp
    print("sorted list:{}".format(unsort_list))

sortalfa(["B", "D", "A", "E", "C"])

Result:

sorted list:['A', 'B', 'C', 'D', 'E']

There are many standard libraries available by which can be done using single line of code.




回答9:


I have tried something like this but I'm not sure about time complexity of program.

l=['a','c','b','f','e','z','s']
l1=[]
while l:
    min=l[0]
    for i in l:
        # here **ord** means we get the ascii value of particular character.
        if ord(min)>ord(i):
            min=i
     l1.append(min)
     l.remove(min)
print(l1)


来源:https://stackoverflow.com/questions/13101468/python-how-to-sort-the-alphabet-in-a-list-without-sorted-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!