
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Different Integers in a String Using Python
Suppose we have a lowercase alphanumeric string s. We shave to replace every non-digit character with a space, but now we are left with some integers that are separated by at least one space. We have to find the number of different integers after performing the replacement operations on s. Here two numbers are considered as different if their decimal representations without any leading zeros are different.
So, if the input is like s = "ab12fg012th5er67", then the output will be 3 because, there are few numbers ["12", "012", "5", "67"] now "12" and "012" are different in string but same as integer. So there are three distinct numbers.
To solve this, we will follow these steps −
nums := a new list
k := blank string
-
for i in range 0 to size of s, do
-
if ASCII of s[i] > 47 and ASCII of s[i] < 58, then
k := k concatenate s[i]
-
otherwise,
-
if k is not a blank string, then
insert integer form of k at the end of nums
k := blank string
-
-
-
if k is not a blank string, then
insert integer form of k at the end of nums
return count of distinct elements in nums
Let us see the following implementation to get better understanding −
Example
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))
Input
"ab12fg012th5er67"
Output
3