Reputation: 99
What is the simple way to count the indexes(locations) of overlap characters identically between two string?
def overlap(string1, string2):
count = 0
for i in range(0,len(string1)-len(string2)+1):
if string2 in string1[i:i+len(string2)]:
count = count +1
return count
I realize I have some issues with my function. Could someone please point out and explain? That would be so helpful!
sample:
overlap('abcb','dbeb') #output >>> 2, not 4
overlap('','winter') #output >>> 0.
Upvotes: 0
Views: 68
Reputation: 2691
Since the strings can have different lengths, use the minimum length. Then compare them using array indexes, character by character. Conceptually:
def overlap(string1, string2):
count=0
for i in range(min(len(string1),len(string2))):
if string1[i] == string2[i]:
count += 1
return count
You could implement it with the zip
built-in function (look at python documentation).
Upvotes: 1