Find longest consecutive letter and digit substring in Python

PythonServer Side ProgrammingProgramming

A given string may be a mixture of digits and letters. In this article we are required to find the biggest substring that has letters and digits together.

with re module

The regular expression module can be used to find all the continuous substring having digits or letters. Then we apply the max function to pick only those continuous substrings of letters and digits which have maximum length among all the substrings found. The findall function is also use to identify and get the required substrings.

Example

 Live Demo

import re

def longSubstring(str):
   letter = max(re.findall(r'\D+', str), key=len)
   digit = max(re.findall(r'\d+', str), key=len)

   return letter, digit

str = 'Hello 459 Congratulations! 234'
print(longSubstring(str))

Output

Running the above code gives us the following result −

(' Congratulations! ', '459')

With len() and While Loop

This is a straight but slow approach in which we design while loops to check the length of digits and letters present as substring in the given string. Then we compare their lengths and choose only the substrings with maximum length.

Example

 Live Demo

def longSubstring(s):
   max_letterSeq = ''
   max_digitSeq = ''
   i = 0
   while (i < len(s)):

      current_letterSeq = ''
      current_digitSeq = ''

      # Letters
      while (i < len(s) and s[i].isalpha()):
         current_letterSeq += s[i]
         i += 1

      # Digits
      while (i < len(s) and s[i].isdigit()):
         current_digitSeq += s[i]
         i += 1

      # Check if not digit or alphabet
      if (i < len(s) and not (s[i].isdigit())
            and not (s[i].isalpha())):
         i += 1

      if (len(current_letterSeq) > len(max_letterSeq)):
         max_letterSeq = current_letterSeq

      if (len(current_digitSeq) > len(max_digitSeq)):
         max_digitSeq = current_digitSeq

   return max_letterSeq, max_digitSeq

str = 'Hello 459 Congratulations! 234'
print(longSubstring(str))

Output

Running the above code gives us the following result −

('Congratulations', '459')
raja
Updated on 26-Aug-2020 08:00:29

Advertisements