Consecutive Character Sequences

George Sakkis gsakkis at rutgers.edu
Thu Jul 14 01:22:29 EDT 2005


"Walter Brunswick" <walterbrunswick at sympatico.ca> wrote:

> Is there any way to [efficiently] iterate through a sequence of characters to find N [or more]
consecutive equivalent characters?
>
> So, for example, the string "taaypiqee88adbbba" would return 1 if the number (of consequtive
characters) supplied in the parameters
> of the function call was 2 or 3, because "a", "e", 8, and "b" is repeated 2 or 3 times.
>
> Thanks for any assistance.
> W. Brunswick.

If you're in 2.4, use itertools.groupby:

import itertools as it

def hasConsequent(aString, minConsequent):
    for _,group in it.groupby(aString):
        if len(list(group)) >= minConsequent:
            return True
    return False


George





More information about the Python-list mailing list