Python Practice › String Programs › Program 45
Least frequent character
Write a Python program to find the least frequent character in a string.
Input
"abcdabdggfhf"
Output
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})Approach
- Count characters and take the one with the smallest count.
Solution
from collections import Counter text = "abcdabdggfhf"counts = Counter(text)print(min(counts, key=counts.get), counts)Output
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})Line by line
Line 5
key=counts.get compares characters by their counts; with ties, the first seen wins.
Learn the concept
New to this topic? Read the lesson, then come back.