DEV Community

orenovadia
orenovadia

Posted on

4

Chunked Iterator: Python Riddle

I really like this python riddle. And it is (almost) a practical problem.

Say you have an iterator (stream of objects of unknown length). And you want to separate it to equal size chunks. An example: splitting a file to multiple smaller sized files.

Doing the same with lists is much easier because the length of the list is known:

from typing import List, TypeVar

T = TypeVar('T')


def chunks(l: List[T], n: int) -> List[List[T]]:
    return [l[i:i + n]
            for i in range(0, len(l), n)]


items = list(range(10))
print(chunks(items, 3))
# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
print(chunks(items, 4))
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

The riddle is: write chunks where the input is an iterator. And the output is an iterator of iterators


def chunks(l: Iterator[T], n: int) -> Iterator[Iterator[T]]:
    ????

I will add the solution later today or tomorrow.

Extra points for run-time performance

Followup question: What problem can you spot in the solution to this problem?

Enjoy

Edit: Solution is here

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay