Python solution using itertools (7 lines)


#1

We can use groupby in itertools to split the string (example: "122334" will become ["1", "22", "33", "4"] Once you have that array, rest is trivial).

from itertools import groupby
def countAndSay(self, A):
    t="1"
    for i in range(1,A):
        a=[''.join(group) for key, group in groupby(t)]
        t=""
        for i in a:
            t=t+str(len(i))+i[0]
    return t

Tip: If you mainly use python, itertools has some very useful functions and It’ll just take a few minutes to learn them

Edit: So, my friend said that it’s actually a 9 line code and I can’t ignore import and the function declaration. If you have the same issue with my code, here’s a 7 liner for you:

class Solution:
    from itertools import groupby    
    def countAndSay(self, A):
        t="1"
        for i in range(1,A):
            t="".join([str(len(j))+j[0] for j in [''.join(group) for key, group in groupby(t)]])
        return t