#!/usr/bin/python3 """Example solution of a programming interview question.""" class VolumeRule: def __init__(self, steps): self.steps = steps def compute(self, volume): for max_volume, rate in self.steps: if volume < max_volume: return volume * rate raise ValueError("volume too huge", volume, steps) class PiecewiseLinearContinuousRule: def __init__(self, steps): self.steps = steps def compute(self, quantity): total = 0 prev_max_qty = 0 for max_qty, rate in self.steps: if max_qty is None: effective_qty = quantity else: effective_qty = min(quantity, max_qty) total += rate * (effective_qty - prev_max_qty) if max_qty is None or quantity < max_qty: break prev_max_qty = max_qty return total rates = dict( crew=PiecewiseLinearContinuousRule([(None, 5)]), volume=VolumeRule([(3, 2), (7, 5), (1000, 21)]), weight=PiecewiseLinearContinuousRule([(10, 1), (15, 2), (None, 10)]), ) def freight(shipment, field): return rates[field].compute(shipment[field]) if __name__ == '__main__': print(freight(dict(weight=4.5, crew=5, volume=37), field='crew')) print(freight(dict(weight=4.5, crew=5, volume=37), field='volume')) print(freight(dict(weight=20, crew=5, volume=37), field='weight')) print(freight(dict(weight=2, crew=5, volume=37), field='weight'))