Program to 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

 Live Demo

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

Updated on: 29-May-2021

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements