- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if the frequency of all the digits in a number is same 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
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
Advertisements