0% found this document useful (0 votes)
34 views

SC-CER96940: "Formando Líderes para La Construcción de Un Nuevo País en Paz"

The document discusses Python functions and related concepts. It explains that Python functions are first-class objects that can be assigned to variables, copied, and passed as arguments. It also covers recursion, using functions as arguments to other functions, and built-in functions like map, filter and reduce. List comprehensions are presented as more readable alternatives to map and filter in many cases. Examples are provided for copying functions, lists of functions, sorting based on function keys, recursion with factorials, and using map, filter, reduce and comprehensions.

Uploaded by

Jorge Quintero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

SC-CER96940: "Formando Líderes para La Construcción de Un Nuevo País en Paz"

The document discusses Python functions and related concepts. It explains that Python functions are first-class objects that can be assigned to variables, copied, and passed as arguments. It also covers recursion, using functions as arguments to other functions, and built-in functions like map, filter and reduce. List comprehensions are presented as more readable alternatives to map and filter in many cases. Examples are provided for copying functions, lists of functions, sorting based on function keys, recursion with factorials, and using map, filter, reduce and comprehensions.

Uploaded by

Jorge Quintero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Reading in English

Theme: working with functions

First-class functions

Python functions are said to be first-class functions, which means they can be assigned to
variables, copied, used as arguments to other functions, etc., just like any other object.

Copying functions. Here is an example where we make a copy of a function:

def f(x):
return x*x
g=f

print('f(3) =', f(3), 'g(3) =', g(3), sep = '\n')

f(3) = 9
g(3) = 9

Lists of functions. Next, we have a list of functions:

def f(x):
return x**2
def g(x):
return x**3
funcs = [f, g]

print(funcs[0](5), funcs[1](5), sep='\n')

25
125

Here is another example. Say you have a program with ten different functions and the
program has to decide at runtime which function to use. One solution is to use ten if
statements. A shorter solution is to use a list of functions. The example below assumes that
we have already created functions f1, f2, . . . , f10, that each take two arguments.

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 1
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
funcs = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]
num = eval(input('Enter a number: '))
funcs[i]((3,5))

Functions as arguments to functions. Say we have a list of 2-tuples. If we sort the list,
the sorting is done based off of the first entry as below:

L = [(5,4), (3,2), (1,7), (8,1)]


L.sort()

[(1, 7), (3, 2), (5, 4), (8, 1)]

Suppose we want the sorting to be done based off the second entry. The sort method takes
an optional argument called key, which is a function that specifies how the sorting should be
done. Here is how to sort based off the second entry:

def comp(x):
return x[1]
L = [(5,4), (3,2), (1,7), (8,1)]
L.sort(key=comp)

[(8, 1), (3, 2), (5, 4), (1, 7)]

Here is another example, where we sort a list of strings by length, rather than alphabetically.

L = ['this', 'is', 'a', 'test', 'of', 'sorting']


L.sort(key=len)

['a', 'is', 'of', 'this', 'test', 'sorting']

Recursion

Recursion is the process where a function calls itself. One of the standard examples of
recursion is the factorial function. The factorial, n!, is the product of all the numbers from 1

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 2
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
up to n. For instance, 5! = 5·4·3·2·1 = 120. Also, by convention, 0! = 1. Recursion involves
defining a function in terms of itself. Notice that, for example, 5! = 5 · 4!, and in general, n! =
n · (n − 1)!. So the factorial function can be defined in terms of itself. Here is a recursive
version of the factorial function:

def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)

We must specify the n = 0 case or else the function would keep calling itself forever (or at
least until Python generates an error about too many levels of recursion).

Note that the math module has a function called factorial, so this version here is just for
demon- stration. Note also that there is a non-recursive way to do the factorial, using a for
loop. It is about as straightforward as the recursive way, but faster. However, for some
problems the recursive so- lution is the more straightforward solution. Here, for example, is
a program that factors a number into prime factors.

def factor(num, L=[]):



for i in range(2,num//2+1):
if num%i==0:

return L+[i]+factor(num//i)
return L+[num]

The factor function takes two arguments: a number to factor, and a list of previously found
factors. It checks for a factor, and if it finds one, it appends it to the list. The recursive part
is that it divides the number by the factor that was found and then appends to the list all the
factors of that value. On the other hand, if the function doesn’t find any factors, it appends
the number to the list, as it must be a prime, and returns the new list.

map, filter, reduce, and list comprehensions

map and filter Python has a built-in functions called map and filter that are used to apply
functions to the contents of a list. They date back to before list comprehensions were a part

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 3
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
of Python, but now list comprehensions can accomplish everything these functions can. Still,
you may occasionally see code using these functions, so it is good to know about them.

The map function takes two arguments—a function and an iterable—and it applies the
function to each element of the iterable, generating a new iterable. Here is an example that
takes a list of strings a returns a list of the lengths of the strings. The first line accomplishes
this with map, while the second line uses list comprehensions:

L = list(map(len, ['this', 'is', 'a', 'test']))



L = [len(word) for word in ['this', 'is', 'a', 'test']]

The function filter takes a function and an iterable and returns an iterable of all the elements
of the list for which the function is true. Here is an example that returns all the words in a list
that have length greater than 2. The first line uses filter to do this, and the second line does
it with a list comprehension:

L = list(filter(lambda x: len(x)>2, ['this', 'is', 'a', 'test']))


L = [word for word in ['this', 'is', 'a', 'test'] if len(word)>2]

Here is one approach to finding the number of items in a list L that are greater than 60:

count=0

for i in L:
if i>60:

count = count + 1

Here is a second way using a list comprehension similar to the filter function:

len([i for i in L if i>60])

The second way is both shorter and easier to understand.

reduce. There is another function, reduce, that applies a function to the contents of a list. It
used to be a built-in function. This function cannot be easily replaced with list
comprehensions. To understand it, first consider a simple example that adds up the numbers
from 1 to 100.

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 4
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
total = 0

for i in range(1,101):
total = total + i

The reduce function can be used to do this in a single line:

total = reduce(lambda x,y: x+y, range(1,101))

In general, reduce takes a function and an iterable, and applies the function to the elements
from left to right, accumulating the result. As another simple example, the factorial function
could be implemented using reduce:

def fact(n):

return reduce(lambda x,y:x*y, range(1,n+1))

Reference: A Practical Introduction to Python Programming. Brian Heinold. Department of


Mathematics and Computer Science Mount St. Mary’s University

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 5
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co

You might also like