Friday 1 January 2021

Python Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

 This is a Python Program to accept a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically.

Problem Description

The program accepts a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically.

Problem Solution

1. Take a hyphen separated sequence of words from the user.
2. Split the words in the input with hyphen as reference and store the words in a list.
3. Sort the words in the list.
4. Join the words in the list with hyphen between them and print the sorted sequence.
5. Exit.

Program/Source Code

Here is source code of the Python Program to accept a hyphen separated sequence of words as input and print the words in a hyphen-separated sequence after sorting them alphabetically. The program output is also shown below.

print("Enter a hyphen separated sequence of words:")
lst=[n for n in raw_input().split('-')]  
lst.sort()
print("Sorted:")
print('-'.join(lst))
Program Explanation

1. User must enter a hyphen separated sequence of words as the input.
2. The sequence is split with the hyphen as the key and the words are stored in a list.
3. The words in the list are sorted alphabetically using the sort() function.
4. The words in the list are then joined using hyphen as the reference.
6. The sorted sequence of words is then printed.

Runtime Test Cases
 
Case 1:
red-green-blue-yellow
Sorted:
blue-green-red-yellow
 
Case 2:
Enter a hyphen separated sequence of words:
Bangalore-hyderabad-delhi
Sorted:
Bangalore-delhi-hyderabad

No comments:

Post a Comment