Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if frequency of each digit is less than the digit in Python
When working with digit frequency validation, we often need to check whether each digit in a number appears no more times than its own value. For example, digit 5 can appear at most 5 times, digit 3 can appear at most 3 times, and so on.
So, if the input is like n = 5162569, then the output will be True as the digits and frequencies are (5, 2), (1, 1), (6, 2), (2, 1) and (9, 1). For all digits, the frequency is less than or equal to the digit value.
Algorithm
To solve this problem, we will follow these steps ?
- For each digit i from 0 to 9, do
- Initialize temp = n and cnt = 0
- While temp is non-zero, do
- If temp mod 10 equals i, then increment cnt
- If cnt > i, return False immediately
- Update temp = temp // 10
- Return True if all digits pass the check
Example
Let us see the following implementation to get better understanding ?
def solve(n):
for i in range(10):
temp = n
cnt = 0
while temp:
if temp % 10 == i:
cnt += 1
if cnt > i:
return False
temp //= 10
return True
# Test the function
s = 5162569
print(f"Number: {s}")
print(f"Result: {solve(s)}")
The output of the above code is ?
Number: 5162569 Result: True
Alternative Approach Using Counter
We can also use Python's Counter class for a more concise solution ?
from collections import Counter
def solve_with_counter(n):
digit_counts = Counter(str(n))
for digit, count in digit_counts.items():
if count > int(digit):
return False
return True
# Test both approaches
test_numbers = [5162569, 1234, 112233]
for num in test_numbers:
result1 = solve(num)
result2 = solve_with_counter(num)
print(f"Number: {num}, Method 1: {result1}, Method 2: {result2}")
The output of the above code is ?
Number: 5162569, Method 1: True, Method 2: True Number: 1234, Method 1: True, Method 2: True Number: 112233, Method 1: False, Method 2: False
How It Works
In the example 5162569:
- Digit 5 appears 2 times (2 ? 5) ?
- Digit 1 appears 1 time (1 ? 1) ?
- Digit 6 appears 2 times (2 ? 6) ?
- Digit 2 appears 1 time (1 ? 2) ?
- Digit 9 appears 1 time (1 ? 9) ?
Since all conditions are satisfied, the function returns True.
Conclusion
Both approaches effectively solve the digit frequency validation problem. The first method uses basic loops and arithmetic operations, while the Counter approach provides cleaner code for counting digit occurrences.
