Python Counter Exercises & Solutions
This resource offers a total of 50 Python counter Data Type problems for practice. It includes 10 main exercises, each accompanied by solutions, detailed explanations, and four related problems.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
[An Editor is available at the bottom of the page to write and execute the scripts.]
1. Counter of Letters
Write a Python program to create a 'Counter' of the letters in the string "Python Exercise!".
Click me to see the sample solution
2. Counter from List Elements
Write a Python program that creates a 'Counter' from a list of elements and print the most common elements along with their counts.
Click me to see the sample solution
3. Counter of Vowels
Write a Python program that creates a counter of the vowels in the word "Python Exercises".
Click me to see the sample solution
4. Counter Union/Intersection/Difference
Write a Python program that creates two 'Counter' objects and finds their union, intersection, and difference.
Click me to see the sample solution
5. Word Frequency Sorting
Write a Python program that creates a counter of the words in a sentence and prints the words in ascending and descending order of their frequency.
Click me to see the sample solution
6. Sum of Two Counters
Write a function that takes two 'Counter' objects and returns their sum.
Click me to see the sample solution
7. Unique Items from Counter
Write a Python program that creates a 'Counter' for a list of items and converts it to a list of unique items with their counts.
Click me to see the sample solution
8. Filter Counter by Threshold
Write a Python program that creates a 'Counter' for a list of words and removes all items with a count less than a certain value.
Click me to see the sample solution
9. Jaccard Similarity Using Counter
Write a python program to find the Jaccard similarity coefficient between two lists using 'Counter' objects.
Click me to see the sample solution
10. Update Counter via Dictionary Access
Write a Python program that creates a 'Counter' for a list of items and uses dictionary-style access to update the count of specific items.
Click me to see the sample solution
Python Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
Test your Python skills with w3resource's quiz