简体   繁体   English

如何在没有内置函数的情况下按字母顺序对字符串进行排序

[英]how to sort a string into alphabetical order without inbuilt functions

My Code:我的代码:

alphabet = "abcdefghijklmnopqrstuvwxyz"
def sort3():
    string = input("please enter a 3 character string: ")
    string1 = string[0]
    string2 = string[1]
    string3 = string[2]
    stringpos1 = alphabet.index(string1)
    stringpos2 = alphabet.index(string2)
    stringpos3 = alphabet.index(string3)
    if stringpos3 > stringpos2 > stringpos1:       # 123
        print(string1 + string2 + string3)
    elif stringpos2 > stringpos3 + stringpos1:     # 132
        print(string1 + string3 + string2)
    elif stringpos3 > stringpos1 > stringpos2:     # 213
        print(string2 + string1 + string3)
    elif stringpos1 > stringpos3 > stringpos2:     # 231
        print(string2 + string3 + string1)
    elif stringpos2 > stringpos1 > stringpos3:     # 312
        print(string3 + string1 + string2)
    elif stringpos1 > stringpos2 > stringpos3:     # 321
        print(string3 + string2 + string1)


sort3()

This is the way i did, i want to know how i can do this for any string (meaning any lengthen string)这就是我所做的,我想知道如何对任何字符串执行此操作(意味着任何加长字符串)

Try this algorithm:试试这个算法:

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



word=input('enter a word: ')
print(''.join(sort(word)))

Example Output:示例输出:

enter a word: xzy
xyz

Works for any length, even:适用于任何长度,甚至:

enter a word: rcrfr sefre erg ergergerg r
    ceeeeeeffggggrrrrrrrrrs

It will be hard to implement your code to any lengthen string很难将您的代码实现为任何加长字符串

Btw, slow way:顺便说一句,缓慢的方式:

from random import shuffle
l=list(input('enter a word: '))

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

sorted_list = l
while True:
   shuffle(sorted_list)
   if is_sorted(sorted_list): break
print(''.join(sorted_list))

First idea is to use a bubble sort implementation:第一个想法是使用冒泡排序实现:

def bubbleSortStr(astr):
    my_list = [x for x in my_str]
    bubbleSort(my_list)
    return ''.join(my_list)

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

my_str = "BubbleSort is cool"
print bubbleSortStr(my_str)
#  BSbbceillooorstu

I took the code for the actual bubble sort from here: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html This is a nice tutorial which explains one of the most basic sorting algorithms.我从这里获取了实际冒泡排序的代码:http: //interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html这是一个很好的教程,它解释了最基本的排序算法之一。

Since the bubble sort example only sorts lists, I had to convert the string into a list which is done in bubbleSortStr().由于冒泡排序示例仅对列表进行排序,因此我必须将字符串转换为在 bubbleSortStr() 中完成的列表。

If we compare the ascii value, then sorting is easy.如果我们比较 ascii 值,那么排序很容易。

Ex:前任:

s = 'apple'

q = list(s)     
['a', 'p', 'p', 'l', 'e']


Code will be : 

for i in range(len(q)):

    for j in range(i+1,len(q)):
        if ord(q[i])>ord(q[j]):
             q[i],q[j] = q[j],q[i]
print(q)

''.join(q) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM