progress

~/problems / Iterators & parsers / Iterators and generators

Iterator with Filter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Coinbase

A dashboard wants only some trades from a price feed (say, above a size threshold). Wrap the feed in an iterator that hands out only the items a test function accepts, in order.

Implement class FilterIterator:

  • FilterIterator(source, keep): source is any iterable (possibly infinite); keep(item) -> bool decides what's wanted.
  • has_next() -> bool: is another wanted item left? It may read ahead, but repeated calls must not skip anything.
  • next(): return the next wanted item, or raise StopIteration.
  • iter(it) returns it and __next__ works like next(), so for and list() work.

Items can be anything, including None, 0 or "". Lazy: keep runs exactly once per item read, and reading stops as soon as the next wanted item is found. Once exhausted, it stays exhausted.

⭐ Bonus: a speed test with 300,000 items earns a star at O(1) work per item read.

it = FilterIterator([4, 7, 10, 3, 8], lambda x: x % 2 == 0)
it.has_next()    # True
it.has_next()    # True (still 4 waiting)
it.next()        # 4
it.next()        # 10
list(it)         # [8]
it.has_next()    # False

import itertools
sq = FilterIterator(itertools.count(1), lambda n: int(n ** 0.5) ** 2 == n)
[sq.next() for _ in range(4)]    # [1, 4, 9, 16]

list(FilterIterator([0, None, "", 5], lambda v: not v))   # [0, None, ""]
Show hint

a one-item buffer plus a separate "buffer is full" flag (a None sentinel breaks when None is a real item). has_next() fills the buffer; next() calls has_next(), then empties it.

Topic: Iterators and generators. Resumable/serializable iterators, merging streams, lazy pipelines.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc