Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order.
Example:
Input : PYTHON
Output : HNOPTY
Input : Geeks
Output : eeGks
Naive Method to sort letters of string alphabetically
Here we are converting the string into list and then finally sorting the entire list alphabet wise.
Python3
s = "GEEKSFORGEEKS"
li = []
l = len (s)
for i in range ( 0 ,l):
li.append(s[i])
for i in range ( 0 ,l):
for j in range ( 0 ,l):
if li[i]<li[j]:
li[i],li[j] = li[j],li[i]
j = ""
for i in range ( 0 ,l):
j = j + li[i]
print (j)
|
Output:
EEEEFGGKKORSS
Using sorted() with join() to sort letters of string alphabetically
Here we are converting the string into a sorted list and then finally joining them using join function.
Python3
def sortString( str ):
return ''.join( sorted ( str ))
str = 'PYTHON'
print (sortString( str ))
|
Output:
HNOPTY
Using sorted() with accumulate() to sort letters of string alphabetically
Here we are importing accumulate from itertools module converting the string into a sorted list, and hence return the result
Python3
from itertools import accumulate
def sortString( str ):
return tuple (accumulate( sorted ( str )))[ - 1 ]
str = 'PYTHON'
print (sortString( str ))
|
Output:
HNOPTY
Using sorted() with reduce() to sort letters of string alphabetically
Another alternative is to use reduce() method. It applies a join function on the sorted list using ‘+’ operator.
Python3
from functools import reduce
def sortString( str ):
return reduce ( lambda a, b : a + b, sorted ( str ))
str = 'PYTHON'
print (sortString( str ))
|
Output:
HNOPTY
When string is in different cases –
Using sorted() with join() to sort letters of string alphabetically
Here we are converting the string into a sorted list and then finally joining them using the lambda functions.
Python3
from itertools import accumulate
def sortString( str ):
return "".join( sorted ( str , key = lambda x:x.lower()))
str = 'Geeks'
print (sortString( str ))
|
Output:
eeGks
Time Complexity: O(n*logn), as sorted() function is used.
Auxiliary Space: O(n), where n is length of string.
Last Updated :
25 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...