Code Explanation:
1) from functools import reduce
Imports the reduce function from the functools module.
reduce repeatedly applies a function to items in a sequence, reducing them to a single value.
2) nums = [2, 3, 4]
Creates a list nums containing three integers: [2, 3, 4].
3) product = reduce(lambda x, y: x * y, nums)
reduce applies the function lambda x, y: x * y (multiplication) cumulatively across nums.
Steps:
First: 2 * 3 = 6
Next: 6 * 4 = 24
So product = 24.
4) nums.append(5)
Adds the number 5 to the list.
Now nums = [2, 3, 4, 5].
5) s = reduce(lambda x, y: x + y, nums, 10)
This uses reduce with an initial value 10.
lambda x, y: x + y adds values together.
Steps:
Start with 10.
10 + 2 = 12
12 + 3 = 15
15 + 4 = 19
19 + 5 = 24
So s = 24.
6) print(product, s)
Prints both results:
product = 24
s = 24
Final Output
24 24
.png)

0 Comments:
Post a Comment