On Thu, Jan 14, 2021 at 2:01 PM Wolfram Hinderer via Python-list < python-list@python.org> wrote:
> Am 13.01.2021 um 22:20 schrieb Bischoop: > > 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 > > > > > You can let itertools.groupy find the groups. > > max((len(tuple(group)), key) for key, group in itertools.groupby(s)) > # (4, 'c') > Does anyone else find the documentation on itertools.groupby kind of lacking? I think it makes sense now that I've played around with it though. Here's a revised solution: def get_longest(string: str) -> typing.Tuple[int, typing.List[str]]: """Get the longest run of a single consecutive character.""" if not string: return (0, []) grouped = itertools.groupby(string) grouped_with_lengths = [(len(list(value)), key) for key, value in grouped] max_count_and_letter = max(grouped_with_lengths) max_count = max_count_and_letter[0] result = (max_count, sorted(list_ for count, list_ in grouped_with_lengths if count == max_count)) return result -- https://mail.python.org/mailman/listinfo/python-list