Python: Accept some words and count the number of distinct words
Python Collections: Exercise-5 with Solution
Write a Python program that accept some words and count the number of distinct words. Print the number of distinct words and number of occurrences for each distinct word according to their appearance.
Sample Solution:
Python Code:
from collections import Counter, OrderedDict
class OrderedCounter(Counter,OrderedDict):
pass
word_array = []
n = int(input("Input number of words: "))
print("Input the words: ")
for i in range(n):
word_array.append(input().strip())
word_ctr = OrderedCounter(word_array)
print(len(word_ctr))
for word in word_ctr:
print(word_ctr[word],end=' ')
Sample Output:
Input number of words: 5 Input the words: Red Green Blue Black White 5 1 1 1 1 1
Flowchart:

Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find the occurrences of 10 most common words in a given text.
Next: Write a Python program that accepts number of subjects, subject names and marks. Input number of subjects and then subject name, marks separated by a space in next line. Print subject name and marks in order of its first occurrence.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Use Reversed() In for Loops:
>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking'] >>> for task in reversed(tasks): ... print(task) ... cooking gardening picking up kids laundry
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion