Advanced OOP and patterns · 9 / 15 Exercise Medium

Discount strategies

Objective

The Strategy pattern separates “which algorithm I use” from “where I use it”: in Python a dictionary that maps a name to a function is enough. Adding a new strategy does not force you to modify the code that uses them.

Instructions

  • The first line has the number n of lines; each one is price strategy [parameter] with the strategy none (no discount), percent p (percentage p) or fixed d (fixed discount; the price does not go below 0).
  • Show Final price: x with 2 decimals.
Input
3
100 none
100 percent 15
100 fixed 30
Output
Final price: 100.00
Final price: 85.00
Final price: 70.00

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise