I have two sequences AAAAAAAAAGAAAAGAAGAAG, AAAGAAG. The correct answer is AAGAAG.
But my code gives AA.
There will also be times when two strings will be in this order AAAGAAG, AAAAAAAAAGAAAAGAAGAAG.
Here is my code
`def longestSubstringFinder(string1, string2):
string1=string1.strip()
string2=string2.strip()
answer = ""
len1=len(string1)
len2=len(string2)
if int(len1)>1 and int(len2)>1:
for i in range(1,len1,1):
match = ""
for j in range(len2):
if len1>len2:
if i+j<len1 and (string1[i+j]==string2[i+j]):
match=str(match)+str(string2[i+j])
print(match)
else:
if len(match)>len(answer):
answer=match
match=""
elif len2>len1:
if i+j<len2 and (string1[i+j]==string2[i+j]):
match=str(match)+str(string2[i+j])
print(match)
else:
if len(match)>len(answer):
answer=match
match=""
return(answer)`
A few weeks ago I've stumbled upon the
difflib
package in Python and it's perfect for this kind of job.Here's a solution to your problem:
The difflib documentation says:
And it's also very fast!
I've timed @AK47 great solution and it timed
10000 loops, best of 3: 85.2 µs per loop
My solution timed
10000 loops, best of 3: 31.6 µs per loop
Get all the substrings of both strings, find the intersection of both sets of substrings and then find the largest string in the intersection