Using map() and filter() Convert Code to solve problems.
Question
Task 1: List Comprehensions
Part A: Convert the Code Using map() and filter() to solve these problems.
• def convert_temp(temp): return (temp-32)/1.8 list(map(convert_temp, [90.0, 50.9, 84.6, 100.3])) • def square(x): return mvP2 def is_odd(i): return 1X2==1 list(map(squaro, list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7]))))
• list(map(int, filter(str.isdigit, ‘c4t,d0g,b144,f15h0))
def convert_tenp(tomps):
Input: Given a list of temperatures in Fahrenheit. Output: A List of values converted all to celsius.
>>> convort_temp([80.0, 50.0, 84.6, 100.3]) [32.22222222222222, 10.499999999999998, 29.222222222222218, 37.944
return [((tomp-32)/1.8) for tamp in temps]
how do you use the filter method to do write the convert_temp function, and why does the answer has the return call on the same line as def? what use does it make?
Summary
Here we have given problems for which we Convert the Code Using map() and filter() to solve these problems. We have to convert the temperature into faranite. Also, have to use the filter method to do write the convert_temp function. And the answer has the return call on the same line with def.
Explanation
We use a filter function when we have to filter a list of elements. So let take an example, If we create a list with all the alphabets letters as elements and we have to take vowels from it. So at that time, we will use the filter function. now this filter function will have two arguments. And they are first is the function name and the second one is the list. Such that now if the function returns true so that element will be on the output list.
And we have a return call on the same line where there is a function header. And that function header will get end by an occurrence of the colon. Then whatever is written after that will be considered as a statement inside the function by the python compiler. So we do not have any benefit through it as well as not the change of having an error.
def convert_temp(temp): return (temp-32)/1.8 print(list(map(convert_temp, [90.0, 50.9, 84.6, 100.3]))) def square(x): return x**2 def is_odd(i): return i%2==1 print(list(map(square, list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7]))))) print(list(map(int, filter(str.isdigit, '1c4t,dog,b14d,f1511'))))
Output:
Also read, Can you fix any mistake on this C program