Functions · 27 / 27 Exercise Medium

Function composition

Objective

Functions are values: they can be stored in a dictionary, passed to another function and returned from a function. With that, simple operations are composed into a more complex one.

Instructions

  • Define four one-argument functions: double_it (double), square_it (square), increment (add 1) and negate (change sign), and store them in a dictionary with the keys "double", "square", "inc" and "neg".
  • Define compose(functions): it receives a list of functions and returns a new function that applies each one to the previous result, in order.
  • Read an integer and then a line with operation names separated by spaces (the line may be empty).
  • Build the composed function with the given operations, apply it to the integer and show Result: x.
Input
3
double square inc
Output
Result: 37

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise