Resumable Iterator
Asked at OpenAI
Reported by the problem's creator, not verified
You are given a list items. Implement the class ResumableIterator that returns the elements of items one at a time and lets the caller save its position and resume from it later.
The iterator's state is the number of elements returned so far: state 0 is the start, and a state equal to the total number of elements is the end. set_state is only ever called with a state from 0 to the total number of elements. Getting or setting the state never changes which element comes next beyond what the state says, and it does not modify items.
Each part builds on the previous ones: every earlier method must keep working as described.
Examples
Example 1
Input: init =
[[1,2,3,4]], operations =[["next",[]],["next",[]],["get_state",[]],["next",[]],["set_state",[2]],["next",[]],["next",[]],["next",[]],["has_next",[]],["next",[]],["get_state",[]]]Output:
[1,2,2,3,null,3,4,"StopIteration",false,"StopIteration",4]Explanation: After two
next()calls the state is 2.set_state(2)puts the iterator back, so the next two calls return 3 and 4 again. After the 4 the iterator is exhausted:has_next()isfalseandnext()raisesStopIteration.