Untitled

mail@pastecode.io avatar
unknown
python
20 days ago
2.4 kB
10
Indexable
Never
# You can call `read()` on the stream and it will return up to `n` ints as an array. 
#It's possible the call will return fewer than `n` values, 
#in which case the stream of data has been consumed completely.

# Example usage on a stream which contains 7 values in total:
# s = Stream(...)  # assume the content is [2, 3, 1, 4, 1, 1, 1]
# s.read(5)  # => returns [2, 3, 1, 4, 1] - full 5-value read as requested
# s.read(3)  # => returns [1, 1] - fewer values than requested
# s.read(4)  # => returns [] - stream is completely exhausted

###### YOUR TASK ########
# Create a new class called `MultiStream` which can store other streams and has a `read()` method that is backed by other streams. 
# Treat `Stream` objects like black boxes - 
# you cannot change their implementation. Implement add(stream),read(n),remove(stream)
# Example usage across two streams containing a total of 6 values:
# ms = MultiStream()
# s1 = Stream(...)
# s2 = Stream(...)
# ms.add(s1)  # first Stream's contents: [5, 4, 1, 4, 5]
# ms.add(s2)  # second Stream's contents: [1, 3]
# ms.read(6)  # => returns [5, 4, 1, 4, 5, 1] - full 5-value read as requested
# ms.remove(s2) # remove [3]
# ms.read(2)  # => returns [] - all streams are completely exhausted
# ms.read(5)  # => still returns [] - all streams are completely exhausted`


from collections import OrderedDict

class ForzenList:
    def __init__(self, list):
        self._list = tuple(list)
    def __hash__(self):
        return hash(self._list)
    def __eq__(self, other):
        return self._list == other._list
        
class Stream:
    def __init__(self):
        self.map = OrderedDict()
        
    def add(self, l):
        key = ForzenList(l)
        self.map[key] = l
        
    def remove(self, l):
        key = ForzenList(l)
        del self.map[key]
        
    def read(self, n:int):
        result = []
        for k in list(self.map.keys()):
            v = self.map[k]
            if len(v) >= n:
                result += v[:n]
                v = v[n:]
                return result
            result += v
            n -= len(v)
            del self.map[k]
        return result

ms = Stream()
s1 = [5, 4, 1, 4, 5]
s2 = [1,3]
ms.add(s1)
ms.add(s2)
assert ms.read(6) == [5, 4, 1, 4, 5, 1]
ms.remove(s2)
assert ms.read(2) == []
assert ms.read(5) == []
s3 = [88, 66, 88]
ms.add(s3)
assert ms.read(5) == [88, 66, 88]
Leave a Comment