# The API: int read4(char *buf) reads 4 characters at a time from a file.## The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.## By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.## Note:# The read function will only be called once for each test case.## The read4 API is already defined for you.# @param buf, a list of characters# @return an integerdefread4(buf):globalfile_contenti=0whilei<len(file_content)andi<4:buf[i]=file_content[i]i+=1iflen(file_content)>4:file_content=file_content[4:]else:file_content=""returniclassSolution(object):defread(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) """start=0buffer=['']*4foriinrange(n/4+1):# how many groups (size == 4 or size < 4)size=read4(buffer)ifsize:buf[start:start+size]=bufferstart+=sizeelse:breakreturnmin(start,n)if__name__=="__main__":answer=Solution()buf=[''foriinrange(100)]file_content="abcdefghijklmnop"printbuf[:answer.read(buf,5)]printbuf[:answer.read(buf,3)]
近期评论