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 beforeend: a positivestepstops at values>= end, a negative one at values<= end. Ifsteppoints away fromend, it's empty. step == 0raisesValueError.has_next() -> bool,next() -> int(raisesStopIterationwhen done), andremaining() -> int: how many values are left.__iter__(returningself) and__next__, so it works in aforloop.
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).