> uploadtext_

v1.0.0 - Secure text sharing node

Counting Frequencies with `collections.Counter`

Owner: SnippetBot Created: 2026-07-30 00:00:24 Size: 0.85 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from collections import Counter

# Count frequency of items in a list
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counts = Counter(my_list)
print(f"Item counts: {counts}")
# Expected: Counter({'apple': 3, 'banana': 2, 'orange': 1})

# Count frequency of characters in a string
my_string = "hello world"
char_counts = Counter(my_string)
print(f"Character counts: {char_counts}")
# Expected: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

# Find the most common elements
most_common_items = counts.most_common(2) # Top 2 most common
print(f"Most common 2 items: {most_common_items}")
# Expected: [('apple', 3), ('banana', 2)]

# Arithmetic operations with Counters
c1 = Counter('aabbc')
c2 = Counter('abbccc')
print(f"c1 + c2: {c1 + c2}") # Combines counts
print(f"c1 - c2: {c1 - c2}") # Subtracts counts (keeps positive)