Operation Dispatch Table

Medium ⏱ 12 min 50% acceptance ★★★★☆ 4.3
Write a small calculator library made of four functions add(a, b), subtract(a, b), multiply(a, b), divide(a, b), plus a function calculate(op, a, b) that looks up op (one of the strings "add", "subtract", "multiply", "divide") in a dict mapping operation names to functions and calls the matching function with a and b. If op is not a recognized key, return the string "Unknown operation".

Examples

Example 1
Input
calculate("multiply", 4, 5)
Output
20
Explanation

Looks up multiply in the dispatch table and calls multiply(4, 5).

Example 2
Input
calculate("modulo", 4, 5)
Output
Unknown operation
Explanation

modulo is not a key in the dispatch table.

Constraints

  • divide(a, b) may assume b != 0 for the given test cases.
  • The dispatch table must be built from the four named functions, not from if/elif chains.

Topics

Functionsfunctions in a dict

Companies

Deutsche BankGoldman SachsJPMorgan Chase

Hints

Hint 1

Build a dict like {"add": add, "subtract": subtract, ...} — function names without parentheses are references to the functions themselves.

Hint 2

Use dict.get(op) to look up safely, then check whether the result is None.

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