Count and Say - The Pythonic way

  • 0

    As n does not get very big, we can derive the n-th solution from the previous ones iteratively.

    Python has the well-known groupby() function in the itertools module which is ideal to solve problems like this.

    The grouping produced by groupby() on the string '11211222' is

    [print(k, list(g)) for k, g in itertools.groupby('11211222')]
    >>> 1 ['1', '1']
    >>> 2 ['2']
    >>> 1 ['1', '1']
    >>> 2 ['2', '2', '2']

    You could then use this results to derive the next sequence, with something similar to

    ''.join([str(len(list(g))) + k for k, g in itertools.groupby(s)])

    which concatenates the length of the group (the number of repetitions of the digit) and the digit itself for each group returned by groupby().

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.