Python Program to Find Longest Common Substring using Dynamic Programming with Bottom-Up Approach

PythonServer Side ProgrammingProgramming

When it is required to find longest common substring using dynamic programming with bottom-up approach, a method can be defined, that computes the solution to smaller problems. These smaller problem results don’t need to be computed again and again. Instead, they can just be accessed when required. This would lead to developing a solution to the bigger problem in hand.

Below is a demonstration for the same −

Example

 Live Demo

def compute_lcw(string_1, string_2):
   val = [[-1]*(len(string_2) + 1) for _ in range(len(string_1) + 1)]
   for i in range(len(string_1) + 1):
      val[i][len(string_2)] = 0
   for j in range(len(string_2)):
      val[len(string_1)][j] = 0
   lcw_i = lcw_j = -1
   lcw_len = 0
   for i in range(len(string_1) - 1, -1, -1):
      for j in range(len(string_2)):
         if string_1[i] != string_2[j]:
            val[i][j] = 0
         else:
            val[i][j] = 1 + val[i + 1][j + 1]
            if lcw_len < val[i][j]:
               lcw_len = val[i][j]
               lcw_i = i
               lcw_j = j
   return lcw_len, lcw_i, lcw_j
string_1 = 'bull'
string_2 = 'bullied'
lcw_len, lcw_i, lcw_j = compute_lcw(string_1, string_2)
print("The longest common substring is : ")
if lcw_len > 0:
   print(string_1[lcw_i:lcw_i + lcw_len])

Output

The longest common substring is :
bull

Explanation

  • A method named ‘compute_lcw’ is defined, that takes two strings as parameter.
  • The two strings are iterated over, and checked to see if any matching string is found in both of them.
  • Even when a single character is found, it is stored in another variable.
  • When this goes on until the end of the string, another string would be common to both these strings.
  • Two strings are defined, and the method is called by passing these two strings.
  • This operation’s data is assigned to a variable.
  • It is then displayed as output on the console.
raja
Published on 11-Mar-2021 12:40:52
Advertisements