Python: Prints the unique words in sorted form from a comma separated sequence of words
Python String: Exercise-14 with Solution
Sort distinct words in comma-separated input.
Write a Python program that accepts a comma-separated sequence of words as input and prints the distinct words in sorted form (alphanumerically).
Sample Solution:
Python Code:
# Prompt the user to input a comma-separated sequence of words and store it in the variable 'items'.
items = input("Input comma-separated sequence of words")
# Split the input 'items' into a list of words by using the comma as the separator and store it in the 'words' list.
words = [word for word in items.split(",")]
# Convert the 'words' list into a set to remove any duplicate words, then convert it back to a list.
# Sort the resulting list alphabetically and join the words with commas.
# Finally, print the sorted and comma-separated list of unique words.
print(",".join(sorted(list(set(words)))))
Sample Output:
Input comma separated sequence of words red, black, pink, green black, green, pink, red
Flowchart:
Python Code Editor:
Previous: Write a Python script that takes input from the user and displays that input back in upper and lower cases.
Next: Write a Python function to create the HTML string with tags around the word(s).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics