progress

~/problems / Iterators & parsers / Iterators and generators

Range Iterator

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

Build RangeIterator(start, end, step=1), a hand-written range (don't use range or itertools inside it).

  • It yields start, start + step, … and stops before end: a positive step stops at values >= end, a negative one at values <= end. If step points away from end, it's empty.
  • step == 0 raises ValueError.
  • has_next() -> bool, next() -> int (raises StopIteration when done), and remaining() -> int: how many values are left.
  • __iter__ (returning self) and __next__, so it works in a for loop.
it = RangeIterator(2, 11, 3)
it.remaining()     # 3
it.next()          # 2
list(it)           # [5, 8]
it.has_next()      # False

list(RangeIterator(10, 0, -4))   # [10, 6, 2]
list(RangeIterator(-3, -3))      # []
list(RangeIterator(5, 1, 2))     # []

⭐ Bonus: a speed test on ranges with about 10**18 values earns a star if the iterator is lazy (constant memory) and every call, remaining() included, is O(1).

Show hint

keep only the next value. The count left is a ceiling division: max(0, (end - cur + step - (1 if step > 0 else -1)) // step).

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

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