Count the number of max consecutive “a”'s from a string. Python 3

后端 未结 5 1153
清酒与你
清酒与你 2021-01-05 08:43

Say that the user inputs:

\"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm\"

How would you go about finding the highest

5条回答
  •  广开言路
    2021-01-05 09:31

    I've seen a couple of regex answers in the comments and the other question, so I'm gonna take a different road. Just getting the count can be done many different ways.

    from itertools import groupby
    
    inp = 'daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm';
    char_groups = groupby(inp, lambda char:char=='a')
    counts = [len(list(group)) for char, group in char_groups]
    # We know every other element of 'counts' is an 'a' element.
    # We just need to know whether to start at zero or one.
    # If inp starts with 'a', start at 0. Otherwise start at 1.
    max(counts[not inp.startswith('a')::2]) # 11
    

    I'm pretty sure both of the regex answers I've seen will replace every string of 'aa+' with two 'a's. If you only want to replace the longest string of 'a's with 'aa' and leave the rest alone:

    char_groups = groupby(inp)
    counts = [(char, len(list(group))) for char, group in char_groups]
    max_idx = max(range(len(counts)), key=lambda i:counts[i][1] if counts[i][0]=='a' else 0)
    result = ''.join(char*count for char, count in counts[:max_idx]) + 'aa' + ''.join(char*count for char, count in counts[max_idx+1:])
    # 'daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaafnnasm'
    

提交回复
热议问题