Skip to content

Commit

Permalink
pushing new solution...
Browse files Browse the repository at this point in the history
  • Loading branch information
dombroks committed Nov 26, 2020
1 parent a09725e commit 238710d
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Microsoft_Problems/Microsoft_Problem_08.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
This problem was asked Microsoft.
Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters.
For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”.
"""


class MyFile:
def __init__(self, contents):
self.contents = contents
self.offset = 0
self.buffer = ""

def read_7(self):
start = self.offset
end = min(self.offset + 7, len(self.contents))
self.offset = end
return self.contents[start:end].strip()

def read_n(self, n):
while len(self.buffer) < n:
extra_chars = self.read_7()
if not extra_chars:
break
self.buffer += extra_chars
n_chars = self.buffer[:n]
self.buffer = self.buffer[n:]
return n_chars.strip()


f = MyFile('Hello world')
assert f.read_7() == "Hello w"
assert f.read_7() == "orld"
assert f.read_7() == ""

f = MyFile("Hello world")
assert f.read_n(8) == "Hello wo"
assert f.read_n(8) == "rld"

0 comments on commit 238710d

Please sign in to comment.