Short Python Solution


  • 0
    U
    # The read4 API is already defined for you.
    # @param buf, a list of characters
    # @return an integer
    # def read4(buf):
    
    class Solution(object):
        def read(self, buf, n):
            """
            :type buf: Destination buffer (List[str])
            :type n: Maximum number of characters to read (int)
            :rtype: The number of characters read (int)
            """
            if n == 0:
                return 0
            
            temp = [""] * 4
            number = min(n, read4(temp))
            ans = number
            buf[:ans] = temp[:ans]
            while number == 4:
                number = min(read4(temp), n - ans)
                buf[ans:ans + number] = temp[:number]
                ans += number
            
            return ans
    

  • -1
    T

    I think your code can be shortened, like this

    class Solution(object):
        def read(self, buf, n):
            """
            :type buf: Destination buffer (List[str])
            :type n: Maximum number of characters to read (int)
            :rtype: The number of characters read (int)
            """
            tmp, ans, num = [""]*4, 0, 4
            while num == 4:
                num = min(n - ans, read4(tmp))
                buf[ans:ans+num] = tmp[:num]
                ans += num
            return ans
    

Log in to reply
 

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