
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to count distinct words and count frequency of them
Suppose we have a list of words. These words may occur multiple times. We have to show the frequencies of these words and count how many distinct words are there.
So, if the input is like words = ["Book", "Sound", "Language", "Computer", "Book", "Language"], then the output will be (4, '2 1 2 1') because there are four distinct words, the first and third words have occurred twice.
To solve this, we will follow these steps −
- d:= an OrderedDict to store items based on insert order
- for each w in words, do
- if w is in d, then
- d[w] := d[w] + 1
- otherwise,
- d[w] := 1
- if w is in d, then
- a pair of the size of list of all keys in d and join all values from d into a string then return.
Example
Let us see the following implementation to get better understanding
from collections import OrderedDict def solve(words): d=OrderedDict() for w in words: if w in d: d[w] += 1 else: d[w] = 1 return len(d.keys()), ' '.join([str(d[k]) for k in d.keys()]) words = ["Book", "Sound", "Language", "Computer", "Book", "Language"] print(solve(words))
Input
["Book", "Sound", "Language", "Computer", "Book", "Language"]
Output
(4, '2 1 2 1')
- Related Articles
- Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
- Get distinct values and count them in MySQL
- Python Program to Count of Words with specific letter
- Python program to count words in a sentence
- Python program to Count words in a given string?
- Program to count number of distinct substrings in s in Python
- Count words in a sentence in Python program
- MySQL SELECT DISTINCT and count?
- MongoDB query to select distinct and count?
- Program to count number of distinct characters of every substring of a string in Python
- Count Frequency of Highest Frequent Elements in Python
- Python – Count frequency of sublist in given list
- Python - Count the frequency of matrix row length
- Program to count number of words we can generate from matrix of letters in Python
- C program to count characters, lines and number of words in a file

Advertisements