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.
Since the bubble sort example only sorts lists, I had to convert the string into a list which is done in bubbleSortStr().
If we compare the ascii value, then sorting is easy.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.