The Custom Iterator
A medium Python interview practice problem on DataDriven. Write and execute real python code with instant grading.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
Implement a Range class accepting (start, stop, step=1) that supports __iter__ and __next__, reimplementing the built-in range() as a custom iterator. The test harness drives your class through a `run_operations(operations, arguments)` driver. `operations` is a list of operation names and `arguments` is a parallel list of positional-argument lists. For each index i: - "Range": construct a new Range with `Range(*arguments[i])` (stash it as the current instance) and append None to the results. - "iterate": collect `list(iter(current_range))` from the most recently constructed Range and append that list to the results. Return the list of per-operation results, in order. __next__ must raise StopIteration when iteration is exhausted: for a positive step, when current >= stop; for a negative step, when current <= stop. So Range(0, 5, 1) yields [0, 1, 2, 3, 4] and Range(10, 0, -2) yields [10, 8, 6, 4, 2].
Summary
Some sequences follow their own rules.
Practice This Problem
Solve this Python problem with real code execution. DataDriven runs your Python code in a real environment and grades it automatically.