Resumable Iterator
OpenAIPhone screenMedium
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.
Part 1: A list iterator with saved state
Implement ResumableIterator over a flat list items of integers and strings.
has_next()returnstruewhile some element has not been returned,falseotherwise.next()returns the next element and advances the state by one. When no element remains, it raisesStopIteration.get_state()returns the number of elements returned so far.set_state(state)moves the iterator so the nextnext()returns the element at indexstate. It returns nothing.
- Example 1
- 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]
Why: 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.
Constraints
0 <= len(items) <= 10^41 <= len(operations) <= 10^4- Each element of
itemsis an integer or a string