Python using a deque


  • 0

    This problem is tagged Hard, and for me the main hard part is how to understand the question:

    1. will read4(ary) totally overwrite ary or only cover the front part? (overwrite)
    2. do I need to return the read result so far or only this time result?(only this time)
    3. what does "The read function may be called multiple times." exactly mean?(a fixed file could be called multiple times read())

    Firstly it's crucial to know what the problem is about. I would like to refer @laonawuli explanation here:

    "
    Think that you have 4 chars "a, b, c, d" in the file, and you want to call your function twice like this:

    read(buf, 1); // should return 'a'
    read(buf, 3); // should return 'b, c, d'
    All the 4 chars will be consumed in the first call. So the tricky part of this question is how can you preserve the remaining 'b, c, d' to the second call.
    "

    Then is doing read(): digest all the existing cached elements before do exactly the same as this one

    from collections import deque
    class Solution(object):
        def __init__(self):
            self.q = collections.deque()
    
        def read(self, buf, n):
            idx, buffer = 0, [''] * 4
            while idx < n and self.q:
                buf[idx], idx = self.q.popleft(), idx + 1
            while idx < n:
                rcnt = read4(buffer)
                if not rcnt:
                    return idx
                buf[idx: idx + rcnt], idx = buffer[:rcnt], idx + rcnt
            if idx > n:
                for i in xrange(n, idx):
                    self.q.append(buf[i])
                buf = buf[:n]
            return n
    

Log in to reply
 

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