A Recent Items List
Advanced · Stretch · from Python Classes and Objects: OOP from the Ground Up
From the lesson: Python Classes and Objects: OOP from the Ground Up
Imagine you own a bakery and you have a cookie cutter shaped like a star. Every time you press it into dough, you get a new star-shaped cookie. The cutter itself isn't a cookie - it's a blueprint for making cookies.
Read the lessonEditors keep a list of the files you opened last. Write a class RecentItems that does the same:
RecentItems(limit) makes an empty list that holds at most limit items.add(item) puts the item at the front. If it is already in the list, it moves to the front instead of appearing twice. If the list is now longer than limit, the oldest item is dropped.items() returns the items as a new list, newest first. Changing that list must not change the object.recent = RecentItems(3)
recent.add("a.py")
recent.add("b.py")
recent.add("a.py")
recent.items() # ['a.py', 'b.py']Some of the tests are hidden.
class RecentItems:
pass
Solution unlocks after your first Check
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| r = RecentItems(3); r.add("a"); r.add("b"); r.add("c"); r.items() | ['c', 'b', 'a'] |
| r = RecentItems(3); r.add("a"); r.add("b"); r.add("a"); r.items() | ['a', 'b'] |
More Classes and Objects exercises
- Create a Book ClassBeginner
- Add a Method to RectangleBeginner
- Predict the Counter OutputBeginner
- Fix the Student ClassIntermediate
- Add __str__ to a ProductIntermediate
- Build a Player Class with Score TrackingIntermediate
- Refactor Functions into a ClassAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz