from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Define a function to add two numbers def add(x, y): return x + y # Use reduce to sum the list of numbers sum_numbers = reduce(add, numbers) print(sum_numbers)
15
from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use reduce with a lambda function to sum the list of numbers sum_numbers = reduce(lambda x, y: x + y, numbers) print(sum_numbers)
15
from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use reduce with a lambda function to calculate the product product_numbers = reduce(lambda x, y: x * y, numbers) print(product_numbers)
120
from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use reduce with a lambda function to sum the list with an initial value sum_numbers = reduce(lambda x, y: x + y, numbers, 10) print(sum_numbers)
25
from functools import reduce # Define a list of numbers numbers = [3, 1, 4, 1, 5, 9] # Use reduce to find the maximum value max_value = reduce(lambda x, y: x if x > y else y, numbers) print(max_value)
9
from functools import reduce # Define a list of lists list_of_lists = [[1, 2], [3, 4], [5, 6]] # Use reduce to flatten the list of lists flattened_list = reduce(lambda x, y: x + y, list_of_lists) print(flattened_list)
[1, 2, 3, 4, 5, 6]
from functools import reduce # Define a list of numbers numbers = [1, 2, 3, 4, 5] # Use map to square each number squared_numbers = map(lambda x: x * x, numbers) # Use filter to select only even squared numbers even_squared_numbers = filter(lambda x: x % 2 == 0, squared_numbers) # Use reduce to sum the even squared numbers sum_even_squared_numbers = reduce(lambda x, y: x + y, even_squared_numbers) print(sum_even_squared_numbers)
20