counting number of (overlapping) occurances

Alex Martelli aleaxit at yahoo.com
Fri Mar 10 01:27:08 EST 2006


John <weekender_ny at yahoo.com> wrote:

> Thanks a lot,
> 
> This works but is a bit slow, I guess I'll have to live with it.
> Any chance this could be sped up in python?

Sure (untested code):

def count_with_overlaps(needle, haystack):
    count = 0
    pos = 0
    while True:
        where = haystack.index(needle, pos)
        if where == -1: return count
        count += 1
        pos = where + 1


Alex



More information about the Python-list mailing list