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
Program to find number of different integers in a string using Python
When working with alphanumeric strings, we often need to extract and count distinct integers. This involves replacing non-digit characters with spaces and identifying unique numbers, where leading zeros don't affect the integer value.
Given a lowercase alphanumeric string, we need to replace every non-digit character with a space, leaving integers separated by spaces. Two numbers are considered the same if their decimal representations without leading zeros are identical.
Example
If the input string is s = "ab12fg012th5er67", we extract numbers ["12", "012", "5", "67"]. Since "12" and "012" represent the same integer value, we have 3 distinct integers: 12, 5, and 67.
Algorithm
The approach follows these steps ?
Create an empty list to store extracted numbers
Use a temporary string to build each number
Iterate through each character in the string
If character is a digit (ASCII 48-57), add it to temporary string
If character is not a digit and temporary string is not empty, convert to integer and add to list
Return count of unique integers using a set
Implementation
def solve(s):
nums = []
k = ""
for i in range(len(s)):
if ord(s[i]) > 47 and ord(s[i]) < 58:
k += s[i]
else:
if k != "":
nums.append(int(k))
k = ""
if k != "":
nums.append(int(k))
return len(set(nums))
s = "ab12fg012th5er67"
print(solve(s))
The output of the above code is ?
3
Alternative Approach Using Regular Expressions
We can simplify the solution using Python's re module to extract all digit sequences ?
import re
def solve_regex(s):
numbers = re.findall(r'\d+', s)
unique_integers = set(int(num) for num in numbers)
return len(unique_integers)
s = "ab12fg012th5er67"
print(solve_regex(s))
print("Extracted numbers:", re.findall(r'\d+', s))
print("Unique integers:", set(int(num) for num in re.findall(r'\d+', s)))
3
Extracted numbers: ['12', '012', '5', '67']
Unique integers: {67, 5, 12}
How It Works
The algorithm processes each character and builds numbers digit by digit. When a non-digit character is encountered, the accumulated number string is converted to an integer, which automatically removes leading zeros. Using a set ensures only unique integers are counted.
Conclusion
Both approaches effectively count distinct integers in a string by extracting digit sequences and converting them to integers. The regular expression method provides cleaner code, while the character-by-character approach offers more control over the parsing process.
