mediumUnit 8 · Functions, Callbacks & lambda
P24. Callback Calculator
Functions, Callbacks & lambda
Write a function calculate(a, b, operation) that returns operation(a, b); here operation is a callback function. Store the supported operations in a dictionary that maps a name to a lambda:
| Name | Operation |
|---|---|
| add | a + b |
| sub | a − b |
| mul | a × b |
| max | the larger of a and b |
| min | the smaller of a and b |
| pow | a to the power b |
Read two integers and a list of operation names. For each name, look up the lambda and pass it to calculate(). If a name is not in the dictionary, print Unsupported.
Input Format
- Line 1:
a b - Line 2: operation names separated by spaces
Output Format
- One line per operation name:
<name>: <result>or<name>: Unsupported
Constraints
- -100 ≤
a,b≤ 100 - For
pow, 0 ≤b≤ 10
Sample Test Cases
Sample 1
Input
6 3 add mul pow
Output
add: 9 mul: 18 pow: 216
Sample 2
Input
4 9 max min div
Output
max: 9 min: 4 div: Unsupported
Submitting checks 2 sample cases and 3 hidden test cases.