-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17_reduce_tutorial.py
More file actions
187 lines (148 loc) · 4.96 KB
/
17_reduce_tutorial.py
File metadata and controls
187 lines (148 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# What is reduce()?
# The reduce(function, iterable, initial) function applies a function to elements of an iterable object
# sequentially, accumulating the result (reduces a list to a single value).
# reduce is in the functools module (not a built-in function!)
from functools import reduce
# 1. Basic example: sum of numbers
numbers = [1, 2, 3, 4, 5]
# Function takes two arguments: accumulator and current element
def add(accumulator, current):
print(f"accumulator: {accumulator}, current: {current}")
return accumulator + current
total = reduce(add, numbers)
print(f"Sum: {total}")
# How it works:
# Step 1: add(1, 2) → 3
# Step 2: add(3, 3) → 6
# Step 3: add(6, 4) → 10
# Step 4: add(10, 5) → 15
# 2. With lambda (more compact)
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, curr: acc + curr, numbers)
print(f"Sum (lambda): {total}")
# 3. With initial value
numbers = [1, 2, 3, 4, 5]
# Third argument - initial accumulator value
total = reduce(lambda acc, curr: acc + curr, numbers, 10)
print(f"Sum with initial 10: {total}") # 10 + 1 + 2 + 3 + 4 + 5 = 25
# 4. Product of numbers
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda acc, curr: acc * curr, numbers)
print(f"Product: {product}") # 1 * 2 * 3 * 4 * 5 = 120
# 5. Finding maximum
numbers = [3, 7, 2, 9, 1, 5]
maximum = reduce(lambda acc, curr: acc if acc > curr else curr, numbers)
print(f"Maximum: {maximum}")
# Equivalent to built-in max() function:
print(f"Maximum (built-in): {max(numbers)}")
# 6. String concatenation
words = ["Python", "is", "awesome"]
sentence = reduce(lambda acc, word: acc + " " + word, words)
print(f"Sentence: {sentence}")
# Better to use join():
sentence_better = " ".join(words)
print(f"Sentence (join): {sentence_better}")
# 7. Merging lists
lists = [[1, 2], [3, 4], [5, 6]]
flattened = reduce(lambda acc, lst: acc + lst, lists)
print(f"Flattened list: {flattened}")
# Modern way (more readable):
flattened_better = [item for sublist in lists for item in sublist]
print(f"Flattened list (comprehension): {flattened_better}")
# 8. Counting elements
fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]
def count_items(acc, item):
acc[item] = acc.get(item, 0) + 1
return acc
counts = reduce(count_items, fruits, {})
print(f"Count: {counts}")
# Better to use Counter:
from collections import Counter
counts_better = Counter(fruits)
print(f"Count (Counter): {dict(counts_better)}")
# 9. Merging dictionaries
dicts = [
{"a": 1, "b": 2},
{"b": 3, "c": 4},
{"d": 5}
]
merged = reduce(lambda acc, d: {**acc, **d}, dicts, {})
print(f"Merged dictionary: {merged}")
# Python 3.9+ (better):
# merged_better = {k: v for d in dicts for k, v in d.items()}
# 10. Nested dictionary access
data = {
"user": {
"profile": {
"name": "Pavel",
"age": 25
}
}
}
# Get value by path ["user", "profile", "name"]
path = ["user", "profile", "name"]
value = reduce(lambda acc, key: acc[key], path, data)
print(f"Value by path: {value}")
# 11. Factorial
def factorial(n):
return reduce(lambda acc, curr: acc * curr, range(1, n + 1))
print(f"5! = {factorial(5)}") # 120
# 12. Comparison with for loop
# reduce
numbers = [1, 2, 3, 4, 5]
total_reduce = reduce(lambda acc, curr: acc + curr, numbers)
print(f"With reduce: {total_reduce}")
# Regular loop (more understandable)
total_loop = 0
for num in numbers:
total_loop += num
print(f"With loop: {total_loop}")
# Built-in function (best!)
total_builtin = sum(numbers)
print(f"With sum(): {total_builtin}")
# 13. Practical example: calculating shopping receipt
items = [
{"name": "Apple", "price": 100, "quantity": 2},
{"name": "Banana", "price": 50, "quantity": 3},
{"name": "Orange", "price": 80, "quantity": 1}
]
# Total cost
total_cost = reduce(
lambda acc, item: acc + item["price"] * item["quantity"],
items,
0
)
print(f"Total cost: {total_cost}")
# 14. Function composition
def add_one(x):
return x + 1
def multiply_by_two(x):
return x * 2
def square(x):
return x ** 2
# Apply functions sequentially
functions = [add_one, multiply_by_two, square]
result = reduce(lambda acc, func: func(acc), functions, 5)
print(f"Composition: {result}") # square(multiply_by_two(add_one(5))) = square(12) = 144
# 15. When to use reduce?
# ✅ Use reduce when:
# - Need to reduce a list to a single value
# - Operation doesn't have a built-in alternative
# - Functional style is required
#
# ❌ DON'T use reduce when:
# - Built-in functions exist (sum, max, min, any, all)
# - Regular loop is more readable
# - Can use list/dict comprehension
#
# Guido van Rossum (Python creator) considers reduce less readable
# and recommends using loops or built-in functions!
# Examples of replacement:
# ❌ reduce(lambda acc, x: acc + x, numbers)
# ✅ sum(numbers)
# ❌ reduce(lambda acc, x: acc if acc > x else x, numbers)
# ✅ max(numbers)
# ❌ reduce(lambda acc, x: acc and x, booleans)
# ✅ all(booleans)
# ❌ reduce(lambda acc, x: acc or x, booleans)
# ✅ any(booleans)