Print all words of a sentence having length n in sorted order :
Given a sentence and a integer n(length of word) , :
The task is to print all the words which are having length n in that sentence in sorted order. :
Examples :
Input : sentence ="keep calm and code on" ; n=4 Output : calm code keep Explanation : Here "keep", "code" ,"calm" are three words which are having length 4 . Input : sentence ="misha walked and looked around" n=6 Output : around looked walked
Approach :
- Scan the sentence and n.
- Store the sentence in list separated by spaces using split() function.
- Sort the list using sort() function.
- Traverse the list
- If the length of word is equal to given length n then print that word
Implementation :
# function to print all words of given length in sorted order
def printSortedWords(lis, n):
# sorting the list
lis.sort()
# traversing the list
for i in lis:
# checking if length of word is equal to n
if(len(i) == n):
# end is used to print with spaces
print(i, end=" ")
# function to split the string
def splitString(string, n):
# split() the string and store in list
lis = list(string.split())
# passing list and given number to printSortedWords function
printSortedWords(lis, n)
# Driver code
n = 4
string = "keep calm and code on"
splitString(string, n)
Output :
calm code keep
Time Complexity : O(n)