Open In App
Related Articles

Python | Sort words of sentence in ascending order

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a sentence, sort it alphabetically in ascending order. 

Examples:

Input : to learn programming refer geeksforgeeks
Output : geeksforgeeks learn programming refer to

Input : geeks for geeks
Output : for geeks geeks

Approach 1 : We will use the built-in library function to sort the words of the sentence in ascending order. 

Prerequisites: 

Follow the steps below:

  • Split the Sentence in words.
  • Sort the words alphabetically
  • Join the sorted words alphabetically to form a new Sentence.

Below is the implementation of the above idea.

Python3

# Function to sort the words
# in ascending order
 
 
def sortedSentence(Sentence):
 
    # Splitting the Sentence into words
    words = Sentence.split(" ")
 
    # Sorting the words
    words.sort()
 
    # Making new Sentence by
    # joining the sorted words
    newSentence = " ".join(words)
 
    # Return newSentence
    return newSentence
 
# Driver's Code
 
 
Sentence = "to learn programming refer geeksforgeeks"
# Print the sortedSentence
print(sortedSentence(Sentence))
 
Sentence = "geeks for geeks"
# Print the sortedSentence
print(sortedSentence(Sentence))

                    

Output
geeksforgeeks learn programming refer to
for geeks geeks

Time Complexity : O(nlogn) , due to built-in sort function used.
Auxiliary Space : O(n) , where n is the total number of characters in string. 

Approach – 2 : 

In this approach we will use the built-in split() method alongside the sorted() function to achieve the same in less lines and less use of functions and methods. We will not use the join() method here.

Python3

def sort_alphabetically(sentence : str) -> list():
   
  s = sentence.split(" ")
   
  return sorted(s)
 
 
sen = "to learn programming refer geeksforgeeks"
print(sort_alphabetically(sen))
 
sen = "geeks for geeks"
print(sort_alphabetically(sen))

                    

Output
['geeksforgeeks', 'learn', 'programming', 'refer', 'to']
['for', 'geeks', 'geeks']

Time Complexity – O(nlogn) # Due to the use of sorted() built in function.
Space Complexity – O(n) # ‘n’ number of characters in string



Last Updated : 17 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads