Function Factory: Choose an Operation at Creation Time

Hard ⏱ 18 min 36% acceptance ★★★★★ 4.6
Write a function make_operator(op_symbol) where op_symbol is one of "+", "-", "*", "/". It should return a new two-argument function that performs the corresponding arithmetic operation. If op_symbol is not recognized, make_operator should raise a ValueError immediately (not when the returned function is later called).

Examples

Example 1
Input
times = make_operator("*")
times(6, 7)
Output
42
Explanation

make_operator("*") returns a function equivalent to multiplication; calling it with 6, 7 gives 42.

Example 2
Input
make_operator("%")
Output
ValueError raised
Explanation

"%" is not one of the four supported symbols, so the error is raised right away, before any function is returned.

Constraints

  • Validation of op_symbol must happen inside make_operator itself, not inside the returned function.
  • The returned function must always take exactly two positional arguments.

Topics

Functionsclosuresfirst-class functions

Companies

MetaApple

Hints

Hint 1

Validate op_symbol with an if/elif chain (or membership check against a set) before defining/returning the inner function.

Hint 2

Define a distinct small inner function per branch, or one inner function that closes over the already-validated op_symbol and branches internally.

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