
PYTHON — Counter Applications in Python
Technology is best when it brings people together. — Matt Mullenweg

PYTHON — Modifying Values Accessor Methods in Python
# Exploring Practical Applications of Python’s Counter Class: Part 2
In the previous lesson, we explored how to count letter frequency in a file and build an ASCII histogram using Python’s Counter class. In this lesson, we will continue exploring more practical applications of the Counter class.
Calculating the Mode
The mode of a sequence is the value that appears most frequently. Let’s write some code to calculate the mode using the Counter class.
from collections import Counter
def mode(data):
freq_counter = Counter(data)
top_count = freq_counter.most_common(1)[0][1]
results = [item for item, count in freq_counter.items() if count == top_count]
return resultsLet’s test the mode calculation function.
data1 = [1, 2, 2, 3]
print(mode(data1)) # Output: [2]
data2 = [2, 2, 3, 3]
print(mode(data2)) # Output: [2, 3]
data3 = ['apples', 'oranges', 'apples', 'oranges', 'apples']
print(mode(data3)) # Output: ['apples', 'oranges']Counting File Types in a Directory
We can also use the Counter class to count the frequency of different file types in a directory.
from collections import Counter
from pathlib import Path
downloads = Path.home() / 'Downloads'
extensions = [file.suffix for file in downloads.iterdir() if file.is_file()]
extension_counter = Counter(extensions)
print(extension_counter.most_common())Using Counter for Shopping Cart
The Counter class can be used to represent a shopping cart, where the keys are the items in the cart and the values are the quantities of each item.
from collections import Counter
prices = {'course': 49.99, 'book': 15.00, 'wallpaper': 2.50}
cart = Counter({'course': 1, 'book': 3, 'wallpaper': 2})
for item, count in cart.items():
price = prices[item]
subtotal = price * count
print(f"{item}: ${price:.2f} x {count} = ${subtotal:.2f}")
# Output:
# course: $49.99 x 1 = $49.99
# book: $15.00 x 3 = $45.00
# wallpaper: $2.50 x 2 = $5.00In this example, we used the items() method to iterate over the Counter object and calculated the subtotal for each item in the cart.
In summary, the Counter class in Python provides a convenient way to perform various counting and frequency-related operations, making it a powerful tool for practical applications such as mode calculation, file type frequency counting, and representing a shopping cart.
In the next lesson, we will explore how to use the Counter class as a multiset implementation.







