Lambda functions, map, filter and reduce Flashcards
String.sort( )
You are given a list of students full names. It is guaranteed that the surname is always the last name of student’s full name.
Your task is to sort the students lexicographically by their surnames. If two students happen to have the same surname, their order in the result should be the same as in the original list.
(Hint: sort + lambda function)
s =[‘Jose Ramirez’, ‘Pedro Martinez’, ‘Alicia Perez’]
students.sort(key=lambda s : s.split()[-1])
sort() stability menas the following is always true: […] If two students happen to have the same surname, their order in the result should be the same as in the original list.
LAMBDA + MAP
Make a function to add all the digits in a number. Show the long and short version of the solution.
n = 12345
#long version suma =0 for d in str(n): suma += int(d)
#short version (can you explain??) digitSum = lambda r: sum(map(int,str(r)))
suma = digitSum(12345)
Implement a function that, given a character ch and the number of times it should be repeated n, returns a string of n characters ch.
tChar = lambda ch, n : ch * n
SYNTAX
def my_function(arguments): statements [...]
Indicate the general syntax for a map function that uses my_function.
map(my_function, iterator)
SYNTAX
Indicate the general syntax for a lambda function
x = lambda arguments : expression
SYNTAX
Indicate the general syntax for the filter function.
new_iter = filter(function, iterator)
MAP
nombres = [‘Jose Buenrostro’, ‘Julio Arturo García’, ‘Maria Antonieta Gonzales’, ‘Ramon Valdes’]
Use map() to construct a list with the last names in nombres[ ]
def explode_name(s): return s.split()
apellidos = [s[-1] for s in map(explode_name, nombres)]