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

Follow graph with snapshots and recommendations

medium 4 levels ~50 min OpenAI

Level 1 Users, follows and snapshots

Build SocialNetwork, a directed "who follows whom" graph, with snapshots that freeze its state.

  • add_user(user): raise ValueError if the user already exists.
  • follow(follower, followee): raise ValueError if either user doesn't exist. Following yourself, or someone you already follow, does nothing.
  • unfollow(follower, followee): raise ValueError if either user doesn't exist; does nothing if there's no such follow.
  • is_following(follower, followee) -> bool: the current state; False for unknown users.
  • create_snapshot() -> Snapshot: a frozen copy of the graph right now.

Snapshot has is_following(follower, followee) -> bool (False for users it doesn't know). A snapshot never sees follows, unfollows or users that happen after it was created.

net = SocialNetwork()
for u in ("ann", "bob", "cy"):
    net.add_user(u)
net.follow("ann", "bob")
snap = net.create_snapshot()
net.follow("ann", "cy")
net.unfollow("ann", "bob")
snap.is_following("ann", "bob")   # True
snap.is_following("ann", "cy")    # False
net.is_following("ann", "bob")    # False
Show hint

Watch out for storing a reference to the live data instead of a copy: a shallow dict.copy() still shares the inner sets.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc