Code Explanation:
๐น Line 1: Import reduce
from functools import reduce
reduce() is imported from the functools module.
๐ reduce() repeatedly applies a function to the elements of an iterable until only one final value remains.
Think of it as:
Value1 + Value2
↓
Result + Value3
↓
Result + Value4
↓
Final Result
๐น Line 2: Create a List
nums = [1, 2, 3, 4]
A list containing four numbers is created.
Current list:
[1, 2, 3, 4]
๐น Line 3: Call reduce()
result = reduce(lambda x, y: x + y * 2, nums)
The lambda function is:
lambda x, y: x + y * 2
It means:
Take the previous result (x)
+
Double the next number (y)
Formula:
x + (y * 2)
๐น Step 1: First Iteration
Initially:
x = 1
y = 2
Calculation:
1 + (2 × 2)
1 + 4
Result:
5
Current result becomes:
5
๐น Step 2: Second Iteration
Now:
x = 5
y = 3
Calculation:
5 + (3 × 2)
5 + 6
Result:
11
Current result:
11
๐น Step 3: Third Iteration
Now:
x = 11
y = 4
Calculation:
11 + (4 × 2)
11 + 8
Result:
19
Current result:
19
๐น Line 4: Print Result
print(result)
Python prints:
19
⚡ Complete Execution Flow
Initial list:
[1, 2, 3, 4]
↓
First step:
1 + (2 × 2)
↓
5
↓
Second step:
5 + (3 × 2)
↓
11
↓
Third step:
11 + (4 × 2)
↓
19
↓
Final Output:
19
๐ Iteration Table
Iteration x y Calculation Result
1 1 2 1 + (2×2) 5
2 5 3 5 + (3×2) 11
3 11 4 11 + (4×2) 19
❌ Common Mistake
Many developers think reduce() calculates:
1 + 2 + 3 + 4
which is:
10
❌ Wrong.
The lambda doubles every new element:
x + y * 2
Because * has higher precedence than +, Python evaluates:
x + (y * 2)
not
(x + y) * 2
๐ก Memory Flow
nums
[1] → [2] → [3] → [4]
↓
1 + 4 = 5
↓
5 + 6 = 11
↓
11 + 8 = 19
↓
result = 19
๐ฏ Final Result
19
✅ Correct Answer
19

0 Comments:
Post a Comment