8.2. Lambda, Filter, Map, and Sorted Solutions#
8.2.1. Exercise 1#
Write a function that squares a number and returns the value. Write it again again using Lambda functions
Show code cell source
def square(num):
return num * num
square2 = lambda num: num * num
print(square(9))
print(square2(9))
81
81
8.2.2. Exercise 2#
Write a lambda function for adding two numbers
Show code cell source
add = lambda a,b: a + b
print(add(3,10))
13
8.2.3. Exercise 3#
Write a lambda function that multiples two numbers. Use the lambda function as an input to another function.
Show code cell source
func = lambda a, b: a * b
def lambda_test(function, number1, number2):
return function(number1, number2)
print(lambda_test(func, 3, 4))
12
8.2.4. Exercise 4#
Write a function to double a list
Use list comprehension to double a list
Use lambda with map to double a list
map objects are a generator. How many times can you iterate over them?
Show code cell source
my_list = [2, 3, 4]
# double this list
# method 1 - define a square function
def square_list(my_list):
new_list = []
for ele in my_list:
new_list.append(ele * ele)
return new_list
print(square_list(my_list))
# method 2 - list comprehension
print([ele*ele for ele in my_list])
# method 3 - use lambda with map
map(lambda variables (comma separated): expression)
print(list(map(lambda ele: ele*ele, my_list)))
# map objects are a generator. How many times can you iterate over them?
Cell In[4], line 21
map(lambda variables (comma separated): expression)
^
SyntaxError: invalid syntax
8.2.5. Exercise 5#
Capitalize the names in the students list
using a list and loop
using list comprehension
using lambda and map
Show code cell source
students = ['john', 'jane', 'doe']
# make upper case
# method 1 create new list and loop
new_list = []
for student in students:
new_list.append(student.title())
print(new_list)
# method 2 -- use list comprehension
print([student[0].upper()+student[1:] for student in students])
# method 3 -- use lambda
print(list(map(lambda student: student.title(), students)))
['John', 'Jane', 'Doe']
['John', 'Jane', 'Doe']
['John', 'Jane', 'Doe']
8.2.6. Exercise 6#
Using lambda and map, convert the numbers to float
Covert each value to float
Show code cell source
my_dict = [{'value': '34.4'}, {'value': '45.3'}, {'value': '73.4'}]
print(list(map(lambda ele: {'Value': float(ele['value'])}, my_dict)))
[{'Value': 34.4}, {'Value': 45.3}, {'Value': 73.4}]
8.2.7. Exercise 7#
Create a dictionary where the key is year and value is True/False if the year is a leap year
using a loop and dict
using filter without a function
Show code cell source
years = range(1970, 2000) # for these years
def is_leap_year(year):
# does not work for century year
if year % 4 == 0:
return True
else:
return False
my_dict = {}
leap_years = []
for year in years:
my_dict.update({year: is_leap_year(year)})
if is_leap_year(year):
leap_years.append(year)
import pprint
pprint.pprint(my_dict)
print(leap_years)
# filter(function, sequence)
leap_year_lambda = lambda year: year % 4 == 0
filter(leap_year_lambda, range(1970, 2000))
print(list(filter(lambda year: year % 4 == 0, range(1970, 2000))))
print(list(filter(lambda year: is_leap_year(year), range(1970, 2000))))
print(list(map(lambda year: year/5, filter(lambda year: year % 4 == 0, range(1970, 2000)))))
# # combining map with filter
print(list(map(lambda year: f'{year} is a leap year!', filter(lambda year: year % 4 == 0, range(1970, 2000)) )))
# # list comprehension
# print()
print([f'{year} is a leap year' for year in range(1970, 2000) if year % 4 == 0])
{1970: False,
1971: False,
1972: True,
1973: False,
1974: False,
1975: False,
1976: True,
1977: False,
1978: False,
1979: False,
1980: True,
1981: False,
1982: False,
1983: False,
1984: True,
1985: False,
1986: False,
1987: False,
1988: True,
1989: False,
1990: False,
1991: False,
1992: True,
1993: False,
1994: False,
1995: False,
1996: True,
1997: False,
1998: False,
1999: False}
[1972, 1976, 1980, 1984, 1988, 1992, 1996]
[1972, 1976, 1980, 1984, 1988, 1992, 1996]
[1972, 1976, 1980, 1984, 1988, 1992, 1996]
[394.4, 395.2, 396.0, 396.8, 397.6, 398.4, 399.2]
['1972 is a leap year!', '1976 is a leap year!', '1980 is a leap year!', '1984 is a leap year!', '1988 is a leap year!', '1992 is a leap year!', '1996 is a leap year!']
['1972 is a leap year', '1976 is a leap year', '1980 is a leap year', '1984 is a leap year', '1988 is a leap year', '1992 is a leap year', '1996 is a leap year']
8.2.8. Exercise 8#
Sort x
using value
Show code cell source
x = (('efg', 1), ('abc', 3), ('hij', 2))
print(sorted(x)) # does work
print(sorted(x, key=lambda ele: ele[1]))
[('abc', 3), ('efg', 1), ('hij', 2)]
[('efg', 1), ('hij', 2), ('abc', 3)]
8.2.9. Exercise 9#
sort dictionary by username; reverse sort
Show code cell source
students = [
{'username': 'john', 'grade': 50},
{'username': 'jane', 'grade': 80},
{'username': 'doe', 'grade': 35},
{'grade': 89, 'username': 'Kelly'}
]
from pprint import pprint
print(sorted(students, key=lambda student: student['username']))
print()
print(sorted(students, key=lambda student: student['username'], reverse=True))
[{'grade': 89, 'username': 'Kelly'}, {'username': 'doe', 'grade': 35}, {'username': 'jane', 'grade': 80}, {'username': 'john', 'grade': 50}]
[{'username': 'john', 'grade': 50}, {'username': 'jane', 'grade': 80}, {'username': 'doe', 'grade': 35}, {'grade': 89, 'username': 'Kelly'}]
8.2.10. Exercise 10#
Sort dictionary by grade; reverse sort
Show code cell source
students = [
{'username': 'john', 'grade': 50},
{'username': 'jane', 'grade': 80},
{'username': 'doe', 'grade': 35},
{'grade': 89, 'username': 'Kelly'}
]
print()
print(sorted(students, key=lambda student: student['grade']))
print()
print(sorted(students, key=lambda student: student['grade'], reverse=True))
[{'username': 'doe', 'grade': 35}, {'username': 'john', 'grade': 50}, {'username': 'jane', 'grade': 80}, {'grade': 89, 'username': 'Kelly'}]
[{'grade': 89, 'username': 'Kelly'}, {'username': 'jane', 'grade': 80}, {'username': 'john', 'grade': 50}, {'username': 'doe', 'grade': 35}]
8.2.11. Exercise 11#
Sort array by len of names
Show code cell source
students = ['john', 'Janette', 'doe']
print(min(students))
print(min(students, key=lambda student: len(student)))
print(max(students, key=lambda student: len(student)))
print(min(students, key=len))
print(max(students, key=len))
Janette
doe
Janette
doe
Janette
8.2.12. Exercise 12#
Sort dictionary by value
Show code cell source
my_list = [{'value': '34.4'}, {'value': '45.3'}, {'value': '73.4'}]
print(max(my_list, key=lambda ele: float(ele['value'])))
{'value': '73.4'}