Syllabus Lesson 128 of 141 · Beat your Ghost
Beat your Ghost

No class: the order life cycle

Why it matters "Model it as an object" is a reflex. Sometimes the rules you are modelling are clearer as a table you can read, print and test on its own.

An online shop receives order events from several systems: payments, the warehouse, the courier. Events can be late, repeated or plain wrong. You replay the event log to find each order's current status and to list the events that should never have happened.

The rules

new       -> paid, cancelled
paid      -> shipped, refunded
shipped   -> delivered, returned
delivered -> returned
returned  -> refunded
cancelled, refunded: final

An order does not exist until its "new" event arrives. In this problem classes are banned: use plain data and functions.

Your turn

Write replay(events). events is a list of (order_id, status) pairs in arrival order. An order's first accepted event must be "new"; after that, an event is accepted only if the table above allows a move from the order's current status to the new one. Anything else is rejected and changes nothing. Return (states, rejected): a dict from order id to its final status (only orders with at least one accepted event), and the list of indices of rejected events, in order. Rule: no class statements (that includes dataclasses and enums).

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.