786. Build an iterator over several lists that can save and restore its state
Long training jobs need data loaders that can resume exactly where they stopped after a crash. The core idea is an iterator whose position can be saved as a small state and restored later.
Write run_iter(lists, mode, ops). lists is a list of lists of items. mode is 'chain' (go through the first list fully, then the second, and so on) or 'round_robin' (take one item from each list in turn, skipping lists that are used up). ops is a list of tuples:
('next',) outputs the next item, or the string 'END' if every list is used up. ('save', name) stores the current state under name. ('restore', name) puts the iterator back to the state saved under name; restoring an unknown name outputs 'ERROR'. A saved state must not change when the iterator keeps moving, and the same saved state can be restored many times.
Return the list of outputs in order (only next and failed restore produce output).
def run_iter(lists, mode, ops)Example 1
Input: run_iter([[1, 2], [3]], 'chain', [('next',), ('save', 's'), ('next',), ('next',), ('restore', 's'), ('next',)])
Output: [1, 2, 3, 2]
Example 2
Input: run_iter([[1, 2, 3], [4], [5, 6]], 'round_robin', [('next',)] * 7)
Output: [1, 4, 5, 2, 6, 3, 'END']
Constraints
- Up to 100 lists and 10,000 operations.
Hint 1
Write next for chain first, then add round robin.
Hint 2
Keep state in plain integers and lists so it is easy to copy.
Hint 3
Copy on save and on restore.
Common mistakes
- Saving a reference to the mutable position list.
- Infinite loop in round robin when all lists are empty.
- Not skipping empty lists in chain mode.
Understand the idea
Make the iterator's position explicit, small and copyable, so checkpointing is just saving that state.