Skip to content Skip to sidebar Skip to footer

Function To Find All Common Substrings In Two Strings Not Giving Correct Output

I am using the following function to find all the common substrings between two strings: def substringFinder(string1, string2): answer = '' anslist=[] len1, len2 = len(

Solution 1:

You can try this:

defsubstrings(s1, s2):
    final = [s1[i:b+1] for i inrange(len(s1)) for b inrange(len(s1))]


    return [i for i in final if i in s1 and i in s2 andlen(i) > 1]

s1, s2 = "ALISSA", "ALYSSA"print(substrings(s1, s2))

Output:

['AL', 'SS', 'SSA', 'SA']

Solution 2:

  1. Don't break
  2. Check the length of the string before adding it to avoid results like "A"
  3. return the function result instead of printing inside the function

Like this:

def substringFinder(string1, string2):
    answer = ""
    anslist=[]
    len1, len2 = len(string1), len(string2)
    for i in range(len1):
        match = ""for j in range(len2):
            if (i + j < len1 and string1[i + j] == string2[j]):
                match += string2[j]
            else:
                #if (len(match) > len(answer)): 
                answer = matchif answer != ''andlen(answer) > 1:
                    anslist.append(answer)
                match = ""ifmatch != '':
            anslist.append(match)
        # breakreturn anslist

print substringFinder("AHAMMAD", "AHAMAD")

result:['AHAM', 'MAD']

Solution 3:

Here is a straightforward brute-force solution:

In [7]: def substring_finder(s1, s2):
   ...:     matches = []
   ...:     size = len(s1)
   ...:     for i in range(2, size):
   ...:         for j in range(0, size, i):
   ...:             stop = j+i
   ...:             if stop > size:
   ...:                 continue
   ...:             sub = s1[j:stop]
   ...:             if sub in s2:
   ...:                 matches.append(sub)
   ...:     return matches
   ...:

In [8]: substring_finder("ALISSA", "ALYSSA")
Out[8]: ['AL', 'SA', 'SSA']

In [9]: substring_finder("AHAMMAD", "AHAMAD")
Out[9]: ['AH', 'AM', 'MA', 'AHA', 'AHAM']

Post a Comment for "Function To Find All Common Substrings In Two Strings Not Giving Correct Output"