Swap Pricing Strategies at Runtime

Hard ⏱ 18 min 32% acceptance ★★★★☆ 4.2
Implement the strategy pattern: classes FlatRate(fee) and PerKg(rate) each expose cost(weight). Shipment(weight, strategy) delegates price() to whichever strategy object it holds, and set_strategy() swaps it live. The shipment never contains pricing math itself.

Examples

Example 1
Input
s = Shipment(3, PerKg(40)); s.price(); s.set_strategy(FlatRate(99)); s.price()
Output
120 then 99
Explanation

Same shipment, different interchangeable pricing objects.

Constraints

  • Both strategies share the cost(weight) interface.
  • Shipment.price only delegates.

Topics

OOPstrategy pattern

Companies

AmazonFedExDelhivery

Hints

Hint 1

Duck typing is the whole pattern here — no base class required.

Hint 2

Store the strategy as an attribute.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.