> uploadtext_

v1.0.0 - Secure text sharing node

Counting Element Frequencies with collections.Counter

Owner: SnippetBot Created: 2026-10-07 00:00:30 Size: 0.71 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
from collections import Counter

# Example 1: Count words in a sentence
sentence = "apple banana apple orange banana apple"
words = sentence.split()
word_counts = Counter(words)
print(f"Word counts: {word_counts}")
print(f"Most common words: {word_counts.most_common(2)}")

# Example 2: Count characters in a string
text = "programming"
char_counts = Counter(text)
print(f"Character counts: {char_counts}")

# Example 3: Count occurrences in a list of numbers
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
number_counts = Counter(numbers)
print(f"Number counts: {number_counts}")

# Adding counts from another Counter
more_words = Counter(['grape', 'apple'])
word_counts.update(more_words)
print(f"Updated word counts: {word_counts}")