Lambda Functions in Python
Source: https://www.w3resource.com/python-exercises/lambda/index.php
Q41
Write a Python program to reverse strings in a given list of string values using lambda.
Original lists:
['Red', 'Green', 'Blue', 'White', 'Black']
Reverse strings of the said given list:
['deR', 'neerG', 'eulB', 'etihW', 'kcalB']
soln
colour_list = ['Red', 'Green', 'Blue', 'White', 'Black']
# three times slower
#rev_colour_list = list(map(lambda x: ''.join(reversed(x)), colour_list))
# quick
rev_colour_list = list(map(lambda x: x[::-1], colour_list))
print(rev_colour_list)
output
['deR', 'neerG', 'eulB', 'etihW', 'kcalB']
Q42
Write a Python program to calculate the product of a given list of numbers using lambda.
list1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Product of the said list numbers:
3628800
list2: [2.2, 4.12, 6.6, 8.1, 8.3]
Product of the said list numbers:
4021.8599520000007
soln
from functools import reduce
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [2.2, 4.12, 6.6, 8.1, 8.3]
product = lambda x, y: x*y
print(f"Product of the said list numbers: {reduce(product, list1)}")
print(f"Product of the said list numbers: {reduce(product, list2)}")
output
Product of the said list numbers: 3628800 Product of the said list numbers: 4021.8599520000007
Q44
Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.
Original Tuple:
((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
Average value of the numbers of the said tuple of tuples:
(30.5, 34.25, 27.0)
Original Tuple:
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
Average value of the numbers of the said tuple of tuples:
(25.5, -18.0, 3.75)
soln
t1 = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
t2 = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
average_idx_tuple_given_list = lambda nt: tuple(map(lambda t: sum(t) / len(t), zip(*nt)))
print(average_idx_tuple_given_list(t1))
print(average_idx_tuple_given_list(t2))
output
(30.5, 34.25, 27.0) (25.5, -18.0, 3.75)
lessons
a couple learning points from this:
- in python, the pointer is actually called a splat:
*
, and it unpacks the given iterator - you can put a lambda in a lambda :D
Q45
Write a Python program to convert string elements to integers inside a given tuple using lambda.
Original tuple values:
(('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34'))
New tuple values:
((233, 33), (1416, 55), (2345, 34))
soln
t3 = (('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34'))
t_to_ints = lambda nt: tuple(map(lambda t: tuple(map(lambda x: int(x), filter(lambda y: y.isdigit(), t))),nt))
print(t_to_ints(t3))
output
((233, 33), (1416, 55), (2345, 34))
comments
my code here was far superior to the w3resource solution. that solution simple indexed into the first and third elements and then converted them to integers, this approach is more robust to n-dimensional tuples.
Q46
Write a Python program to find the index position and value of the maximum and minimum values in a given list of numbers using lambda.
Original list:
[12, 33, 23, 10.11, 67, 89, 45, 66.7, 23, 12, 11, 10.25, 54]
Index position and value of the maximum value of the said list:
(5, 89)
Index position and value of the minimum value of the said list:
(3, 10.11)
soln
l1 = [12, 33, 23, 10.11, 67, 89, 45, 66.7, 23, 12, 11, 10.25, 54]
min_pos_val_t = lambda l: (l.index(min(l)), min(l))
max_pos_val_t = lambda l: (l.index(max(l)), max(l))
print(max_pos_val_t(l1))
print(min_pos_val_t(l1))
output
(5, 89) (3, 10.11)
Q47
Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings.
Original list:
[19, 'red', 12, 'green', 'blue', 10, 'white', 'green', 1]
Sort the said mixed list of integers and strings:
[1, 10, 12, 19, 'blue', 'green', 'green', 'red', 'white']
soln
sort_mixed = lambda sm: sorted(list(filter(lambda x: type(x) == int, sm))) + sorted(list(filter(lambda x: type(x) == str, sm)))
print(sort_mixed([19, 'red', 12, 'green', 'blue', 10, 'white', 'green', 1]))
output
[1, 10, 12, 19, 'blue', 'green', 'green', 'red', 'white']
Q48
Write a Python program to sort a given list of strings (numbers) numerically using lambda.
Original list:
['4', '12', '45', '7', '0', '100', '200', '-12', '-500']
Sort the said list of strings(numbers) numerically:
['-500', '-12', '0', '4', '7', '12', '45', '100', '200']
soln
sort_nums_as_str = lambda nums: list(map(str, sorted(list(map(lambda num: int(num), nums)))))
print(sort_nums_as_str(['4', '12', '45', '7', '0', '100', '200', '-12', '-500']))
output
['-500', '-12', '0', '4', '7', '12', '45', '100', '200']
Q49
Write a Python program to count the occurrences of items in a given list using lambda.
Original list:
[3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]
Count the occurrences of the items in the said list:
{3: 4, 4: 2, 5: 3, 8: 2, 0: 2, 1: 1, 2: 2}
soln
#count_occ = lambda l: dict(sorted({x: l.count(x) for x in set(l)}.items(), key=lambda item: item[1], reverse=True))
#count_occ = lambda l: {x: l.count(x) for x in set(l)}
count_occ = lambda nums: dict(map(lambda el: (el, list(nums).count(el)), nums))
print(count_occ([3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]))
output
{3: 4, 4: 2, 5: 3, 8: 2, 0: 2, 1: 1, 2: 2}
lessons
I struggled with this question a lot. The trick was to create a sequence of tuples and then convert those into the dictionary.
Q50
Write a Python program to remove specific words from a given list using lambda.
Original list:
['orange', 'red', 'green', 'blue', 'white', 'black']
Remove words:
['orange', 'black']
After removing the specified words from the said list:
['red', 'green', 'blue', 'white']
soln
remove_words = lambda lw, rw: [word for word in lw if word not in rw]
print(remove_words(['orange', 'red', 'green', 'blue', 'white', 'black'], ['orange', 'black']))
['red', 'green', 'blue', 'white']
output
lessons
the .remove()
function only takes in an item, not a generator.
Q51
Write a Python program to find the maximum and minimum values in a given list of tuples using the lambda function.
Original list with tuples:
[('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)]
Maximum and minimum values of the said list of tuples:
(74, 62)
soln
max_min_vals = lambda tl: (min(tl, key=lambda item: item[1])[1], max(tl, key=lambda item: item[1])[1])
print(max_min_vals([('V', 62), ('VI', 68), ('VII', 72), ('VIII', 70), ('IX', 74), ('X', 65)]))
output
(62, 74)
Q52
Write a Python program to remove None values from a given list using the lambda function.
Original list:
[12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]
Remove None value from the said list:
[12, 0, 23, -55, 234, 89, 0, 6, -12]
soln
remove_nones = lambda l: [x for x in l if x != None]
print(remove_nones([12, 0, None, 23, None, -55, 234, 89, None, 0, 6, -12]))
output
[12, 0, 23, -55, 234, 89, 0, 6, -12]