CBSE Class 12 Computer Science Question 32 of 56

Functions — Question 32

Back to all questions
32
Question

Question 28

Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.

Sample Items: green-red-yellow-black-white
Expected Result: black-green-red-white-yellow

Solution
def sort_words(s):
    words = s.split('-')
    words.sort()
    return '-'.join(words)

input_str = input('Enter a hyphen-separated sequence of words: ')
print(sort_words(input_str))
Output
Enter a hyphen-separated sequence of words: green-red-yellow-black-white   
black-green-red-white-yellow

Enter a hyphen-separated sequence of words: delhi-bangalore-mumbai-chennai-lucknow-patna
bangalore-chennai-delhi-lucknow-mumbai-patna
Answer

def
sort_words
(
s
):
words
=
s
.
split
(
'-'
)
words
.
sort
()
return
'-'
.
join
(
words
)
input_str
=
input
(
'Enter a hyphen-separated sequence of words: '
)
print
(
sort_words
(
input_str
))
Output
Enter a hyphen-separated sequence of words: green-red-yellow-black-white
black-green-red-white-yellow

Enter a hyphen-separated sequence of words: delhi-bangalore-mumbai-chennai-lucknow-patna
bangalore-chennai-delhi-lucknow-mumbai-patna