In this class we will see a section of Python that gives it great power and that does not exist in other types of languages: functional programming.
In Python you can use functions as if it were another type of data, that is, you can define functions, invoke functions by passing parameters, pass functions as parameters, etc.
suppose we have two functions, one to add and one to subtract defined
def add (x, y):
return x + y
def subtract (x, y):
but we can also define a function that as a parameter has another function
def operate (f, x, y):
return f (x, y)
So we can add two numbers of the form
operate (sum, x, y)
and subtract two number from the form
operate (subtract, x, y)
Of course you can ask yourself why use this type of notation if with traditional programming you can already define functions without passing functions as a parameter?
Functional programming in Python will allow us to make a whole series of constructions and give it functionalities that with other types of languages are more complicated to carry out.
Functional programming is widely used for list processing.
Filter, map and reduce functions
The filter function applies a boolean function to each element of a list creating another list with the elements that meet the condition
large def (x):
return x> 100
filter (large, [5,500,200,20,150])
The map function applies a function to each element of a list creating another list with the result of each operation
def double (x):
return x + x
filter (double, [1,10,50])
The reduce function is perhaps the strangest of the three and consists of applying a function as if it were a sum and taking the parameters of the list by breaking it into two pieces
def multiply (x, y):
return x * y
filter (multiply, [2,3,5])
30 as a result of 2 * 3 * 5
In Python, you can define lists with so-called generators, which are objects that allow you to use instantiated list values only when they are used.
At first it is confusing but the idea is not to create the list at the moment of definition but only partially when it is used.
This is very convenient for large lists that otherwise used a lot of memory.
to create a list of the first 1000 numbers we could use
In Python you can use a special notation to create a list from another call Comprehensions
The notation is
[f (x) for x in list]
and that defines a list by applying a function to each element of the given list
[2 * x for x in range (10,15)]
I would give the list
A condition of the form can also be applied
[f (x) for x in list if condition]
[2 * x for x in range (10,15) if x% 2 = 0]
I would give the list (list of even elements only)
This type of notation at first is difficult to understand and apply but once mastered it gives enough power to the language.