def _fetch_next(itr: Iterable[X], n: int) -> Iterable[Tuple[X, ...]]: """ Creates generator. Each element is tuple of size "n". While iterating, first element will be first "n" elements of Stream, next element will be old "n-1" elements appended with next element of Stream and so on. Note that if in first call to this generator, stream has less than "n" element then ValueError will be thrown. :param itr: :param n: a natural number :return: """ if n < 1: raise ValueError("'n' must be natural number") chunk = get_chunk(itr, n) if len(chunk) != n: # first chunk size must be "n". raise ValueError("Stream has less than '{}' elements ".format(n)) yield chunk for e in itr: chunk = chunk[1:] + (e,) yield chunk
def test_1(self): rnd = random() a, b, size = 0, 10, 10 chunk_size = 3 data = rnd.int_range(a, b, size=size) itr = iter(data.copy()) for i in range(a, b, chunk_size): chunk = get_chunk(itr, chunk_size, list) self.assertListEqual(chunk, data[i:i + chunk_size])
def test_8(self): data = range(10) get_chunk(data, range(5, 3)) # should throw exception
def test_5(self): data = range(10) get_chunk(data, 0) # should throw exception
def test_4(self): data = range(10) get_chunk(data, None) # should throw exception
def test_2(self): data = () self.assertEqual(get_chunk(data, 3), ())