Lambda functions are crucial in functional programming as they allow the production of neat and concise functions that require other functions as an argument. You should be familiar with lambda functions from previous courses on Python, but if you are not (or would like a refresher), this exercise will serve as a brief review.
A lambda function is a short anonymous function that can accept several parameters but only returns one value. Lambdas can be stored as a variable or defined inline in the accepting function.
Consider the following example:
We determine the cost of a two-dimensional sheet of metal by multiplying the price per square-meter times the area of the sheet. We can cut the sheet into either a rectangle or a triangle. To model this, let’s write a general function in Python that calculates the price of a sheet of metal. The function will accept the following parameters:
- price per square-meter
- a tuple of dimensions,
- a function to compute area. The function will return the price of a sheet of metal.
Recall from geometry:
- Area of a triangle: 0.5 * (base * height)
- Area of a rectangle: base * height
Writing the function without lambdas, we have:
def rect(b, h): return b * h def tri(b, h): return 0.5 * (b * h) # ppsm: price per square meter # dim: dimensions tuple def total_cost(ppsm, dim, area): return ppsm * area(dim, dim) print(total_cost(3, (5, 5), rect)) # Rectangular sheet costing 75 units print(total_cost(4, (6, 7), tri)) # Rectangular sheet costing 84 units
To make the code shorter, we can replace the
rect(b,h) and the
tri(b,h) functions with lambdas like so:
# ppsm: price per square meter # dim: dimensions tuple def total_cost(ppsm, dim, area): return ppsm * area(dim, dim) print(total_cost(3, (5, 5), lambda b, h: b*h)) # Rectangular sheet costing 75 units print(total_cost(4, (6, 7), lambda b, h: 0. 5 * b*h)) # Rectangular sheet costing 84 units
Lambda functions can be stored in a variable like so:
rect = lambda x, y: x * y tri = lambda x, y: 0.5 * x * y
Lambdas are a very powerful tool in Python. However, they have a drawback in that they are only suited for “short and fast” functions. Long, complicated functions cannot be written as lambdas.
odd_or_even() function provided. The body of the function will return
n is even and return
n is odd.
Convert the functions
cubed(x) into lambdas stored in variables called
For this checkpoint, odd numbers are to be squared and even numbers are to be cubed! Create a variable called
test and set it to
n being 5 and pass in
cube in the appropriate locations.