Run a number through a list of named operations.
What to build
A function that builds and returns another function.
Requirements
- The operations are
double,inc(add 1),squareandneg(change the sign). - Write
compose(names), which returns a function that applies those operations in order. - Read a number and then a line of names, and print the result.
Input
Two lines: a whole number, then one or more operation names separated by spaces.
Output
One number.
Constraints
The number is from -100 to 100, and there are at most 6 operations.
Example
Input:
3
double inc
Output:
7
Why it works
compose returns a function that remembers names. The pipeline is built once and could be used on any number of values.
Examples
Example 1 · Input
3 double inc
Expected output
7
Example 2 · Input
3 inc double
Expected output
8
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the operations in a dictionary, from name to function.
Hint 2
Write compose(names), which returns a new function.
Hint 3
The returned function loops over the names and updates a value step by step.
Solution
Show one correct solution (try it yourself first)
ops = {
"double": lambda x: x * 2,
"inc": lambda x: x + 1,
"square": lambda x: x * x,
"neg": lambda x: -x,
}
def compose(names):
def run(x):
for name in names:
x = ops[name](x)
return x
return run
value = int(input())
pipeline = compose(input().split())
print(pipeline(value))