Lambda functions, map, filter and reduce Flashcards

1
Q

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)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

LAMBDA + MAP

Make a function to add all the digits in a number. Show the long and short version of the solution.

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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.

A

tChar = lambda ch, n : ch * n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

SYNTAX

def my_function(arguments):
    statements [...]

Indicate the general syntax for a map function that uses my_function.

A

map(my_function, iterator)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

SYNTAX

Indicate the general syntax for a lambda function

A

x = lambda arguments : expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

SYNTAX

Indicate the general syntax for the filter function.

A

new_iter = filter(function, iterator)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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[ ]

A
def explode_name(s):
    return s.split()

apellidos = [s[-1] for s in map(explode_name, nombres)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly