count consecutive elements

Dan Stromberg drsalists at gmail.com
Wed Jan 13 21:20:11 EST 2021


On Wed, Jan 13, 2021 at 5:59 PM Tim Chase <python.list at tim.thechases.com>
wrote:

> On 2021-01-13 21:20, Bischoop wrote:
> > I want to  to display a number or an alphabet which appears mostly
> > consecutive in a given string or numbers or both
> > Examples
> > s= ' aabskaaabadcccc'
> > output: c
> > # c appears 4 consecutive times
> >  8bbakebaoa
> > output: b
> > #b appears 2 consecutive times
>

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

HTH


More information about the Python-list mailing list