9-line 61ms AC python solution with comments


  • 9
    S
    class Solution:
        def read(self, buf, n):
            idx = 0
            while True:
                buf4 = [""]*4
                curr = min(read4(buf4),n-idx)  # curr is the number of chars that reads
                for i in xrange(curr):
                    buf[idx] = buf4[i]
                    idx+=1
                if curr!=4 or idx==n:  # return if it reaches the end of file or reaches n
                    return idx

  • 1
    C

    Nice solution, just one comment, the final "if" clause you only need to check whether curr != 4 (or curr < 4).


  • -1
    I

    1 line shorter version:

    class Solution(object):
        def read(self, buf, n):
            idx=0
            buf4=['c']*4
            while True:
                curr=min(read4(buf4),n-idx)
                buf[idx:idx+curr]=buf4
                idx+=curr
                if curr<4:
                    return idx
    

  • 0
    D

    Improved version. More concise.
    7-line, 46 ms.

        def read(self, buf, n):
            read, need, buffer = 0, n, ['']*4
            while need > 0:
                k = read4(buffer)
                need = min(k, n - read)
                buf[read:read+need] = buffer[:need]
                read += need
            return read
    

  • 0

    For this kind of problem, it's not the shorter, the better. The solutions @SherLockey and @dichen001 posted has no engineering sense.


  • 0
    G

    Stupid question! I just want to clear the buffer it gives:

    class Solution(object):
        def read(self, res, n):
            res[:] = []
            inp = [''] * 4
            while True:
                cnt = read4(inp)
                if not cnt: return len(res)
                for i in xrange(cnt):
                    if len(res) == n: return n
                    res.append(inp[i])
    

Log in to reply
 

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