count consecutive elements

Tim Chase python.list at tim.thechases.com
Wed Jan 13 22:37:42 EST 2021


On 2021-01-13 18:20, Dan Stromberg wrote:
> I'm kind of partial to:
> 
> import collections
> import typing
> 
> 
> def get_longest(string: str) -> typing.Tuple[int, str]:
>     """Get the longest run of a single consecutive character."""
>     dict_: typing.DefaultDict[str, int] =
> collections.defaultdict(int) for left_ch, right_ch in zip(string,
> string[1:]): if left_ch == right_ch:
>             dict_[left_ch] += 1
> 
>     maximum = max((value, key) for key, value in dict_.items())
> 
>     return maximum

seems to only return one value so seems to get odd results if I
specify something like

  get_longest("aaabcccbbb")

which at least here tells me that "c" is the longest run, even though
aaa, bbb, and ccc are all runs of length 3.  The OP didn't specify
what should happen in that case, so it would need some clarification.

-tkc





More information about the Python-list mailing list