14. Keep the Last N Events
Difficulty: Medium · Topic: Core Python & data structures
Write last_n(events, n): return the last n items of events as a list, oldest first.
eventscan be any iterable, including a generator reading a log far too large to hold in memory: keep at mostnitems at a time.nis 0 or more. With fewer thannevents, return them all.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
last_n(['a', 'b', 'c', 'd', 'e'], 3)Expected: ['c', 'd', 'e']
Hints
Hint 1
A generator cannot be sliced, andlist(events) would hold the whole log.Hint 2
collections.deque(iterable, maxlen=n) keeps only the newest n items: adding one more drops the oldest.Hint 3
Watchn = 0: xs[-0:] is the whole list, because -0 is 0.Learn the concepts
- Counter, defaultdict and deque · 6 min read. Count, group and keep the last N with the collections module, and the traps in each.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium