Python solution with explainations and comments


  • 6
    Z

    Simplified from solution to #158 in this post

    i.e., easy to extend to multi-call case

    def read(self, buf, n):
        idx = 0
        while n > 0:
            # read file to buf4
            buf4 = [""]*4
            l = read4(buf4)
            # if no more char in file, return
            if not l:
                return idx
            # write buf4 into buf directly
            for i in range(min(l, n)):
                buf[idx] = buf4[i]
                idx += 1
                n -= 1
        return idx
    

  • 1
    Z

    I don't understand this question, also the answer, why write buf4 to buf while buf4 is list of empty strings and buf is a parameter? can you explain? Thank you !


  • 3
    F

    I think the actual file that read4 reads from is hidden from us. read4 reads the file and put it in buf4 and chars in buf4 are put into buf again.


  • 0
    W

    what is the step " buf4 = [""]*4 " for?
    What are the parameter requirements for read4 API? I tried to change the buf4 into "buf4 = []" but error occurs. The question description said nothing about the input type for read4, how did you figure it out?


  • 0
    Z

    When I got stuck, I usually referred to others' solutions, and tried to learned from it.

    This problem is not well defined for python. You should be able to ask reviewer to clarify the problem in an interview.


  • 2
    J

    I like your Python solution the most. Here is a slightly modified version that may be a bit more clear:

    def read(self, buf, n):
        i = 0
        while i < n: 
            buf4 = ['','','','']
            count = read4(buf4) # Read file into buf4.
            if not count: break # EOF
            count = min(count, n - i)
            buf[i:] = buf4[:count] # Copy from buf4 to buf.
            i += count
        return i
    

Log in to reply
 

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