user248237dfsf user248237dfsf - 1 year ago 80
Python Question

Counting longest occurence of repeated sequence in Python

What's the easiest way to count the longest consecutive repeat of a certain character in a string? For example, the longest consecutive repeat of "b" in the following string:

my_str = "abcdefgfaabbbffbbbbbbfgbb"

would be 6, since other consecutive repeats are shorter (3 and 2, respectively.) How can I do this in Python?


Answer Source

How about a regex example:

import re
my_str = "abcdefgfaabbbffbbbbbbfgbb"
len(max(re.compile("(b+b)*").findall(my_str))) #changed the regex from (b+b) to (b+b)*
# max([len(i) for i in re.compile("(b+b)").findall(my_str)]) also works

Edit, Mine vs. interjays

x=timeit.Timer(stmt='import itertools;my_str = "abcdefgfaabbbffbbbbbbfgbb";max(len(list(y)) for (c,y) in itertools.groupby(my_str) if c=="b")')

x=timeit.Timer(stmt='import re;my_str = "abcdefgfaabbbffbbbbbbfgbb";len(max(re.compile("(b+b)").findall(my_str)))')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download