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
Nice solution, just one comment, the final "if" clause you only need to check whether curr != 4 (or curr < 4).
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
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
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.