Well. fdj
will be matched because it is the first 3 characters of the string? Or does it come from somewhere else? If you have more then 2 occurences of your needle
, do you need the distance between the first 2 matches, or the first and the last, or all the distances for each couple of matches?
Well, I can give you a function that gives you all the matches.
>>> def find_matches(needle, hackstay):
... '''returns a list of positions of needle in hackstay'''
... ptr = 0
... found = []
... while True:
... idx = hackstay[ptr:].find(needle)
... if idx < 0: return found
... found.append(ptr+idx)
... ptr += idx+len(needle)
...
>>>
>>>
>>> find_matches('fdj','fdjhkajajkfdj')
[0, 10]
Distance between 2 elements of the array is just the bigger element minus the smaller element minus the length of needle.
Example:
>>> res = find_matches('fdj','fdjhkajajkfdj')
>>> distance = abs(res[0]-res[1])-len('fdj')
>>> print distance
7
With this you can decide by yourself, where needle
comes from and what distances you need. Hope it helps!
PS: If anybody can suggest how to improve that code, please do! My feeling says that this can be written shorter (like using found = [i for ??? if ???]
), but I don't know, how.