Insane Python Solution

  • 3

    Actually, in hindsight it feels somewhat obvious and straightforward, but while I was developing it, I felt like madness :-D

    class Solution(object):
        def __init__(self):
            self.chars = itertools.chain.from_iterable(iter(lambda buf=[0]*4: buf[:read4(buf)], []))
        def read(self, buf, n):
            return len([buf.__setitem__(*x) for x in zip(range(n), self.chars)])

    Note that self.chars is completely lazy, (re)filling its small buffer with read4 on the fly only as needed. But read uses unnecessarily much extra space due to range, zip and the list comprehension, so that's suboptimal. Doing it as follows makes the whole solution use only O(1) space:

    def read(self, buf, n):
        return sum(buf.__setitem__(*x) or 1 for x in itertools.izip(xrange(n), self.chars))

  • 1

    You're INSANE!!!! I really dig it!

  • 0

    My favorite part, the iter(lambda buf=[0]*4: buf[:read4(buf)], []), might actually be the first time I ever used iter(callable, sentinel) :-). I should probably use it more often...

Log in to reply

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