Calculator Dispatch Table

Medium ⏱ 12 min 46% acceptance ★★★★☆ 4.3
Write calculate(op, a, b) supporting '+', '-', '*', '/' by looking the operator up in a dict of lambdas (no if/elif chain). Dividing by zero must return the string 'error' instead of raising.

Examples

Example 1
Input
calculate('*', 6, 7)
Output
42
Explanation

The * lambda multiplies.

Example 2
Input
calculate('/', 5, 0)
Output
'error'
Explanation

Guarded zero-division.

Constraints

  • No if/elif for operator selection.
  • Unknown operators may raise KeyError.

Topics

Lambda & Functionaldict of lambdas

Companies

Morgan StanleyJPMorgan ChaseWipro

Hints

Hint 1

Build {op: lambda} once, then index it.

Hint 2

The / lambda can itself use a conditional expression.

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