Skip to content

Commit 838c8a1

Browse files
authored
Merge pull request #9 from dantp-ai/solution/task0_3
Implement reduce
2 parents 7ba29fd + 2037d13 commit 838c8a1

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

minitorch/operators.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -197,17 +197,21 @@ def reduce(
197197
$x_1 \ldots x_n$ and computes the reduction :math:`fn(x_3, fn(x_2,
198198
fn(x_1, x_0)))`
199199
"""
200-
# TODO: Implement for Task 0.3.
201-
raise NotImplementedError("Need to implement for Task 0.3")
200+
201+
def new_fn(ls: Iterable[float]) -> float:
202+
res = start
203+
for x in ls:
204+
res = fn(res, x)
205+
return res
206+
207+
return new_fn
202208

203209

204210
def sum(ls: Iterable[float]) -> float:
205211
"Sum up a list using `reduce` and `add`."
206-
# TODO: Implement for Task 0.3.
207-
raise NotImplementedError("Need to implement for Task 0.3")
212+
return reduce(add, 0)(ls)
208213

209214

210215
def prod(ls: Iterable[float]) -> float:
211216
"Product of a list using `reduce` and `mul`."
212-
# TODO: Implement for Task 0.3.
213-
raise NotImplementedError("Need to implement for Task 0.3")
217+
return reduce(mul, 1)(ls)

tests/test_operators.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,7 @@ def test_sum_distribute(ls1: List[float], ls2: List[float]) -> None:
198198
Write a test that ensures that the sum of `ls1` plus the sum of `ls2`
199199
is the same as the sum of each element of `ls1` plus each element of `ls2`.
200200
"""
201-
# TODO: Implement for Task 0.3.
202-
raise NotImplementedError("Need to implement for Task 0.3")
201+
assert_close(sum(ls1) + sum(ls2), sum(addLists(ls1, ls2)))
203202

204203

205204
@pytest.mark.task0_3

0 commit comments

Comments
 (0)