12 Line Python Solution


  • 0
    L
    def countAndSay(self, n):
        curr = "1"
        while n > 1:
            nxt = ""
            while len(curr) > 0:
                ch = curr[0]
                num = sum(1 for _ in takewhile(lambda x: x == ch, curr))
                curr = curr[num:]
                nxt = nxt + "{0}{1}".format(ch, num)
            curr = nxt
            n = n - 1
        return curr

  • 0
    D

    You forgot to count your import line.

    from itertools import takewhile
    

    Really overkilling for such an easy task

    Take a look at below: 11 lines with a second while loop

    def countAndSay(self, n):
        p, n = "1", n - 1
        while n:
            q, idx, l = '', 0, len(p)
            while idx < l:
                start, idx = idx, idx + 1
                while idx < l and p[idx] == p[start]:
                    idx += 1
                q += str(idx-start) + p[start]
            n, p = n - 1, q
        return p

  • 0
    C

    should be format(num, ch)


Log in to reply
 

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