Python Practice › Loop Programs › Program 26

Frequency of each digit

MediumLoop Programs · 26 of 90

Write a Python program to find how often each digit appears in an integer.

Advertisement
Input
1223334441
Output
1 -> 2
2 -> 2
3 -> 3
4 -> 3

Approach

  1. Use a dictionary of counts, filled one digit at a time.

Solution

Python
n = 1223334441counts = {}while n > 0:    d = n % 10    counts[d] = counts.get(d, 0) + 1    n //= 10for digit in sorted(counts):    print(digit, "->", counts[digit])
Output
1 -> 2
2 -> 2
3 -> 3
4 -> 3

Line by line

Line 5

get(d, 0) returns 0 the first time a digit is seen.

Line 7

Sorting the keys prints the digits in order.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs