Code Explanation:
1. Importing reduce
from functools import reduce
reduce is a higher-order function from Python’s functools module.
It reduces an iterable (like a list) to a single value by repeatedly applying a function.
2. Importing operator module
import operator
The operator module provides function versions of Python operators.
Example:
operator.add(a, b) is the same as a + b.
operator.mul(a, b) is the same as a * b.
3. Defining the list
nums = [2, 3, 5]
A list of integers [2, 3, 5] is created.
This is the sequence we’ll reduce using addition.
4. Using reduce with initial value
res = reduce(operator.add, nums, 10)
General form of reduce:
reduce(function, iterable, initial)
Here:
function = operator.add (adds two numbers).
iterable = nums = [2, 3, 5].
initial = 10 (starting value).
Step-by-step execution:
Start with 10 (the initial value).
Apply operator.add(10, 2) → result = 12.
Apply operator.add(12, 3) → result = 15.
Apply operator.add(15, 5) → result = 20.
So the final result is 20.
5. Printing the result
print(res)
Prints the reduced value, which is 20.
Final Output
20
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment