LC 0157 [E] Read N Characters Given Read4 - ALawliet/algorithms GitHub Wiki

// incase input string is longer than n. // Let's say your file length is 10, but n = 7, you are not going to fetch 10 and return 10, you have to stop at 7.

"""
The read4 API is already defined for you.

    @param buf4, a list of characters
    @return an integer
    def read4(buf4):

# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf4 = [' '] * 4 # Create buffer with enough space to store characters
read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""

class Solution:
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Number of characters to read (int)
        :rtype: The number of actual characters read (int)
        """
        fp = 0
        while fp < n: 
            buf4 = ['','','','']
            readn = read4(buf4) # Read file into buf4.
            if not readn: break # EOF
            readn = min(readn, n - fp)
            buf[fp:] = buf4[:readn] # Copy from buf4 to buf.
            fp += readn
        return fp