[英]how to sort a string into alphabetical order without inbuilt functions
我的代码:
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()
这就是我所做的,我想知道如何对任何字符串执行此操作(意味着任何加长字符串)
试试这个算法:
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)))
示例输出:
enter a word: xzy
xyz
适用于任何长度,甚至:
enter a word: rcrfr sefre erg ergergerg r
ceeeeeeffggggrrrrrrrrrs
很难将您的代码实现为任何加长字符串
顺便说一句,缓慢的方式:
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))
第一个想法是使用冒泡排序实现:
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
我从这里获取了实际冒泡排序的代码:http: //interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html这是一个很好的教程,它解释了最基本的排序算法之一。
由于冒泡排序示例仅对列表进行排序,因此我必须将字符串转换为在 bubbleSortStr() 中完成的列表。
如果我们比较 ascii 值,那么排序很容易。
前任:
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.