w3resource

Python counter filter program: Counting and filtering words

Python Counter Data Type: Exercise-8 with Solution

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.

Sample Solution:

Code:

from collections import Counter

def main():
    colors = ["Red", "Green", "Black", "Black", "Red", "red", "Orange", "Pink", "Pink", "Red", "White"]
    color_counter = Counter(colors)
    
    min_count = 2
    filtered_counter = {word: count for word, count in color_counter.items() if count >= min_count}
    
    print("Original List:", colors)
    print("Counter:", color_counter)
    print(f"Items with Count >= {min_count}:", filtered_counter)

if __name__ == "__main__":
    main()

Output:

Original List: ['Red', 'Green', 'Black', 'Black', 'Red', 'red', 'Orange', 'Pink', 'Pink', 'Red', 'White']
Counter: Counter({'Red': 3, 'Black': 2, 'Pink': 2, 'Green': 1, 'red': 1, 'Orange': 1, 'White': 1})
Items with Count >= 2: {'Red': 3, 'Black': 2, 'Pink': 2}

In the exercise above, the "Counter" class is used to create a counter for the list of words. The 'filtered_counter' is then created by filtering out items with a count less than the specified 'min_count' from the original counter. Finally results are displayed, including the original list, the counter, and filtered items exceeding or equal to 'min_count'.

Flowchart:

Flowchart: Python counter filter program: Counting and filtering words.

Previous: Python Program: Convert counter to list of unique Items.
Next: Python Program: Calculate Jaccard Similarity Coefficient.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/extended-data-types/python-extended-data-types-index-counter-exercise-8.php