0

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.
2
  • oh yes, thanks for advice Commented Feb 28, 2016 at 16:22
  • 1
    What is your current code's output, what would be the expected output? Are you looking for the same thing as question Overlapping count of substring in a string in Python, maybe? Commented Feb 28, 2016 at 17:00

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help and explanation. I think I understand it now. Wasn't thought about the minimum length. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.