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.
markzzzz
  • 89
  • 1
  • 6
  • oh yes, thanks for advice – markzzzz Feb 28 '16 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](http://stackoverflow.com/questions/32283255/overlapping-count-of-substring-in-a-string-in-python), maybe? – das-g Feb 28 '16 at 17:00

1 Answers1

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

Sci Prog
  • 2,651
  • 1
  • 10
  • 18
  • Thanks for help and explanation. I think I understand it now. Wasn't thought about the minimum length. ;) – markzzzz Feb 28 '16 at 18:26