Function to find all common substrings in two strings not giving correct output

Viewed 3643

I am using the following function to find all the common substrings between two strings:

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]
                j=j+1
            else:
                #if (len(match) > len(answer)): 
                answer = match
                if answer != '':
                    anslist.append(answer)
                match = ""

        if match != '':
            anslist.append(match)
        break
    print(anslist)

So when I do substringFinder("ALISSA", "ALYSSA") is gives ['AL', 'SSA'] which is fine. But when I do substringFinder("AHAMMAD", "AHAMAD"), it only gives output ['AHAM'] but I want ['AHAM', 'MAD'] as output. How to get that?

3 Answers
Related