progress

~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

Greenhouse watering rota

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A greenhouse volunteer wants a tool that says which plants need water today: a fern every 3 days, a cactus every 10. Days are integers.

Implement class Greenhouse:

  • add_plant(name, every, day): pot a plant on day (that counts as a watering). ValueError if name exists or every isn't a positive integer.
  • water(name, day): record a watering. KeyError if unknown; ValueError if day is before its last watering (the same day is fine).
  • remove_plant(name): KeyError if unknown.
  • due(day) -> list[str]: plants whose next watering (last + every) is on or before day, most overdue first, ties by name A→Z.

A call that raises must leave the greenhouse unchanged.

g = Greenhouse()
g.add_plant("fern", 3, day=0)
g.add_plant("cactus", 10, day=0)
g.add_plant("basil", 1, day=2)
g.due(3)             # ["basil", "fern"]   both due exactly on day 3
g.water("fern", 4)
g.due(5)             # ["basil"]           fern is next due on day 7
g.due(12)            # ["basil", "fern", "cactus"]   overdue by 9, 5 and 2 days
g.water("fern", 1)   # ValueError: earlier than day 4
g.add_plant("fern", 2, day=5)   # ValueError: already exists
g.water("mint", 5)   # KeyError
Show hint

a dict from name to a small record (every, last); check everything before assigning; due is a filter plus sorted(..., key=lambda n: (-overdue, n)).

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc