How to merge two strings based on shared suffix and prefix in Python

2 Answers

0 votes
def merge_on_overlap(s1: str, s2: str) -> str:
    max_possible_overlap_len = min(len(s1), len(s2))

    for i in range(1, max_possible_overlap_len + 1):
        if s1.endswith(s2[:i]):
            return s1 + s2[i:]
         
    return s1 + s2

print(merge_on_overlap("fantasy time travel technology", "technology extraterrestrial life"))

   
'''
run:
   
fantasy time travel technology extraterrestrial life
   
'''

 



answered Jan 23 by avibootz
edited Jan 23 by avibootz
0 votes
def merge_on_overlap(s1: str, s2: str) -> str:
    max_possible_overlap_len = min(len(s1), len(s2))

    for i in range(1, max_possible_overlap_len + 1):
        if s1.endswith(s2[:i]):
            return s1 + s2[i:]
         
    return s1 + s2

print(merge_on_overlap("FantasyTimeTravelTechnology", "TechnologyExtraterrestrialLife"))

   
'''
run:

FantasyTimeTravelTechnologyExtraterrestrialLife
   
'''

 



answered Jan 23 by avibootz
edited Jan 23 by avibootz
...