runtime
338 / 500
question 338 Functional & Dynamic Python · medium

From an if/elif chain to a registry

to_base(value, unit) converts food label amounts to grams or kilocalories with a growing if/elif chain. Refactor it so the conversions live in a dictionary CONVERSIONS from unit to a function, and to_base only looks the unit up. Behaviour must stay exactly the same, including the ValueError for an unknown unit, and a unit added to CONVERSIONS later must work without changing to_base.

Functionto_base(value, unit), same results as the original
CONVERSIONSa dictionary from unit ("g", "kg", "mg", "oz", "kcal", "kj") to a function of the value
Unknown unitValueError("unknown unit: lb")
Examples
callto_base(20.5, 'oz')returns581.1652240625
callto_base(1523, 'kj')returns364.0057361376673
callto_base(0.5, 'kg')returns500.0

Loading your progress…

From an if/elif chain to a registry — Python practice · Runtime