Python Practice › String Programs › Program 45

Least frequent character

EasyString Programs · 45 of 106

Write a Python program to find the least frequent character in a string.

Advertisement
Input
"abcdabdggfhf"
Output
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})

Approach

  1. Count characters and take the one with the smallest count.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment