Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have the following two strings: "Hey there" and "there is a ball"

I want the output to be True, because the first one ends with "there" and the second one begins with "there".

Also, it would be helpful if I could know the length of the overlap.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should work:

def endOverlap(a, b):
    for i in range(0, len(a)):
        if b.startswith(a[-i:]):
            return i
    return 0

a = "Hey there"
b = "there is a ball"
c = "here is a ball"
d = "not here is a ball"

print(a, b, endOverlap(a, b))
print(a, c, endOverlap(a, c))
print(a, d, endOverlap(a, d))

Edit: modified to return length of overlap and to be more efficient if only small parts of the string are expected to overlap. Then fixed a bug.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...