Check Frequency of All Digits in a Number in Python



Suppose we have a number num we have to check whether is balanced or not. A number is balanced when frequencies of all digits are same or not.

So, if the input is like num = 562256, then the output will be True as frequency of each digit is 2.

To solve this, we will follow these steps −

  • number := convert num as string
  • freq := a map containing frequencies of digits of number
  • freq_values := make a new set by taking all digit frequency values from number
  • if size of freq_values is same as 1, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

from collections import defaultdict

def solve(num):
   number = str(num)
 
   freq = defaultdict(int)
   n = len(number)
 
   for i in range(n):
      freq[int(number[i])] += 1
 
   freq_values = set(freq.values())
 
   if len(freq_values) == 1:
      return True
   return False
   
num = 562256
print(solve(num))

Input

562256

Output

True
Updated on: 2021-01-15T06:40:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements