BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features41 of 54 in topic

786. Build an iterator over several lists that can save and restore its state

MediumData processing and features Pro

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).

Functiondef 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.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
786 / 903
Python 3solution.pyPython idle
1
2
3
4
def run_iter(lists, mode, ops):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS