Fill in the Blanks: Fill in the blanks for the following code so that it takes in a parameter of “x” and returns “true” if it is greater than 50; otherwise, it should return “False”:
>>> ____ x _ True if x _ 50 ____ False
Degree Conversion: Write a lambda function that takes in a degree value in Celsius and returns the degree converted into Fahrenheit.
today we were able to understand the differences between normal functions and anonymous functions, otherwise known as lambda functions. they’re useful for readability and being able to condense your code. one of their most powerful features is being able to give functions more capabilities by being returned from them.
Wednesday: Map, Filter, and Reduce
When working with data, you’ll generally need to be able to modify, filter, or calculate an expression from the data. That’s where these important built-in functions come in to play. The map function is used to iterate over a data collection and modify it. The filter function is used to iterate over a data collection, and you guessed it… filter out data that doesn’t meet a condition. Lastly, the reduce function takes a data collection and condenses it down to a single result, like the sum function for lists.
To follow along with this lesson, let’s continue from our notebook file “Week_08” and simply add a markdown cell at the bottom that says, “Map, Reduce, and Filter.”
The map function is used when you need to alter all items within an iterable data collection. It takes in two arguments, the function to be applied on each element and the iterable data. When using map, it returns a map object, which is an iterator. Don’t worry about what these are for now; just know that we can type convert them into a data type that we can work with, like a list. Let’s try taking in a list of Celsius temperatures and convert all of them to Fahrenheit:
1| # using the map function without lambdas 2| def convertDeg(C):
3| return (9/5) * C + 32
4| temps = [ 12.5, 13.6, 15, 9.2 ]
5| converted_temps = map(convertDeg, temps) # returns map object
6| print(converted_temps)
7| converted_temps = list(converted_temps) # type convert map object into list of converted temps
8| print(converted_temps)
Go ahead and run the cell. The first print statement will output “” or something similar. This is because the map function returns a map object, not a converted data collection. On line 7, we’re able to convert the map object into a list, which results in the output of “[ 54.5, 56.48, 59, 48.56 ]”. When map is called, the function begins to iterate over the the temps list passed in. As it iterates, it passed a single item into the convertDeg function until it passes all items in. The equivalent of the process is the following:
>>> for item in temps:
>>> convertDeg(item)
Following the conversion, it appends the data to the map object. It isn’t until we convert the map object that we’re able to see the converted temperatures.
Do'stlaringiz bilan baham: |