Python solution using takewhile

  • -1
    def countAndSay(self, n):
        from itertools import takewhile, islice
        def generate_next(seq):
            i, result = 0, []
            while i < len(seq):
                for j, d in enumerate(takewhile(lambda x: x == seq[i], seq[i:])):
                i += j + 1
                result += [str(j+1), d]
            return ''.join(result)
        def generate():
            cur = '1'
            while True:
                yield cur
                cur = generate_next(cur)
        return next(islice(generate(), n-1, None))

  • 0
    This post is deleted!

Log in to reply

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