Frequency Counting Techniques
Advanced Frequency Counting Methods
1. Using collections.Counter
The most efficient and Pythonic way to count frequencies is using Counter
:
from collections import Counter
numbers = [1, 2, 3, 1, 2, 1, 4, 5, 2]
freq_counter = Counter(numbers)
## Most common elements
print(freq_counter.most_common(2))
## Total frequency of an element
print(freq_counter[1])
Frequency Counting Strategies
graph LR
A[Input List] --> B{Frequency Counting Method}
B --> C[Counter]
B --> D[Dictionary]
B --> E[Set + Count]
2. Manual Dictionary Frequency Tracking
def track_frequencies(items):
freq_dict = {}
for item in items:
freq_dict[item] = freq_dict.get(item, 0) + 1
return freq_dict
words = ['python', 'java', 'python', 'javascript', 'python']
frequencies = track_frequencies(words)
print(frequencies)
Method |
Time Complexity |
Memory Efficiency |
Ease of Use |
Counter |
O(n) |
High |
Very High |
Manual Dictionary |
O(n) |
Medium |
Medium |
List Comprehension |
O(nÂē) |
Low |
Low |
3. Functional Approach with defaultdict
from collections import defaultdict
def frequency_tracking(data):
freq = defaultdict(int)
for item in data:
freq[item] += 1
return dict(freq)
scores = [85, 90, 85, 92, 78, 90, 85]
score_frequencies = frequency_tracking(scores)
print(score_frequencies)
Advanced Filtering Techniques
from collections import Counter
data = [1, 2, 3, 1, 2, 1, 4, 5, 2]
counter = Counter(data)
## Filter elements with frequency > 2
high_freq_elements = {k: v for k, v in counter.items() if v > 2}
print(high_freq_elements)
Key Insights
Counter
is the most recommended method
- Choose frequency tracking based on specific requirements
- Consider performance and readability
LabEx recommends mastering these techniques for efficient Python programming.