Consecutive Character Sequences

mensanator at aol.com mensanator at aol.com
Thu Jul 14 03:34:01 CEST 2005



Walter Brunswick 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.

def rep(n):
    # current repetition count
    the_rep = 1
    # previous character inspected
    last_c = ''
    # history of repetions
    max_rep = {}
    for c in s:
        # duplicate character found?
        if c==last_c:
            # count how many consecutive dups
            the_rep += 1
        # repetition (if any) ended, save previous rep count
        else:
            # has this count occured before?
            if max_rep.has_key(the_rep):
                # if so, track how many times it has
                max_rep[the_rep] += 1
            # otherwise, add this rep count to history
            else:
                max_rep[the_rep] = 1
                # reset rep count to look for next block
                the_rep = 1
        # save current character to compare to next character
        last_c = c
    # check that last character in string wasn't part of a block
    if max_rep.has_key(the_rep):
        max_rep[the_rep] += 1
    else:
        max_rep[the_rep] = 1
    # finally, did the block size we asked for ever occur?
    if max_rep.has_key(n):
        return 1
    else:
        return 0

s = 'taaypiqee88adbbba'

for i in range(9):
    print rep(i),


"""

0 1 1 1 0 0 0 0 0

"""




More information about the Python-list mailing list