counting number of (overlapping) occurances

Alex Martelli aleaxit at yahoo.com
Fri Mar 10 07:54:04 CET 2006


Alex Martelli <aleaxit at yahoo.com> wrote:

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

Oops -- 'find', not 'index' -- sorry (it WAS untested;-).

>         if where == -1: return count
>         count += 1
>         pos = where + 1


Alex



More information about the Python-list mailing list