Write A Program To Check The Overlapping Of One String's Suffix With The Prefix Of Another String
a = input() b = input() def longestSubstringFinder(string1, string2): answer = '' len1, len2 = len(string1), len(string2) for i in range(len1): match = ''
Solution 1:
Using RegEX, you can do it with lesser lines of code. I'm assuming you're a beginner in Python. If you are, then please learn RegEx and List Comprehension for this type of code.
import re
str1, str2 = input(), input()
deflongestSubstringFinder(string1, string2):
list_of_subsets = [str1.replace(str1[:i], '') for i inrange(len(str1))]
intersect = [re.search('^'+slc, str2).group() for slc in list_of_subsets if re.search('^'+slc, str2)]
iflen(intersect) == 0:
return'No overlapping'else:
return intersect[0]
print(longestSubstringFinder(str1, str2))
Solution 2:
Some issues:
- the
else
block should not allow the inner loop to continue: when you have a mismatch, you should not try matches with higher values ofj
, but you should exit that loop and try with the next value fori
. So there needs to be abreak
in theelse
block - the condition
len(match) > len(answer)
is not enough to identify a solution. The reason for getting into theelse
block might have been that the characters didn't match, so in that case you should never updateanswer
. - On the other hand, the update of
answer
is not happening now when the inner loop ends normally, i.e. when all compared characters were equal andi + j < len1
was always true. This case happens when the second input string is a suffix of the first. So you must make the update toanswer
somewhere else, so you also catch this case.
Here is the correction to your code, dealing with these issues:
deflongestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i inrange(len1):
match = ""for j inrange(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
# Move the assignment to answer here, and add condition that# this was the last character of string1:if i + j == len1 - 1andlen(match) > len(answer): answer = match
else:
break# Necessary!if answer == '':
return'No overlapping'else:
return answer
With the use of string slicing, and comparing those slices instead of individual characters, you can make your code shorter and run faster.
Post a Comment for "Write A Program To Check The Overlapping Of One String's Suffix With The Prefix Of Another String"