Calculator with a dictionary

Evaluate commands such as add 3 4. The operations are add, sub, mul, max and min. Store them in a dictionary of functions instead of writing a chain of if/elif.

What to build

A calculator in which adding a new operation takes only one new line.

Requirements

  • Store the operations in a dictionary of functions.
  • Look up each command's name and call the function.

Input

The first line has n (1 to 100). Each of the next n lines is an operation name and two whole numbers.

Output

One result per command.

Constraints

n is from 1 to 100.

Example

Input:

2
add 3 4
mul 3 4

Output:

7
12

Why it works

The dictionary maps a name directly to behaviour, so the program never needs a chain of if tests.

Examples

Example 1 · Input
2
add 3 4
mul 3 4
Expected output
7
12
Example 2 · Input
1
max -1 -5
Expected output
-1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Each dictionary value can be a lambda or a built-in such as max.

Hint 2

ops[name] gets the function; (a, b) calls it.

Solution

Show one correct solution (try it yourself first)
ops = {
    "add": lambda a, b: a + b,
    "sub": lambda a, b: a - b,
    "mul": lambda a, b: a * b,
    "max": max,
    "min": min,
}

n = int(input())
for _ in range(n):
    name, a, b = input().split()
    print(ops[name](int(a), int(b)))

Lesson: Functions as values →