Skip to content

Commit 7ba29fd

Browse files
authored
Merge pull request #8 from dantp-ai/solution/task0_3
Implement map
2 parents 852fc98 + c220469 commit 7ba29fd

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

minitorch/operators.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -142,14 +142,16 @@ def map(fn: Callable[[float], float]) -> Callable[[Iterable[float]], Iterable[fl
142142
A function that takes a list, applies `fn` to each element, and returns a
143143
new list
144144
"""
145-
# TODO: Implement for Task 0.3.
146-
raise NotImplementedError("Need to implement for Task 0.3")
145+
146+
def new_fn(ls: Iterable[float]) -> Iterable[float]:
147+
return [fn(x) for x in ls]
148+
149+
return new_fn
147150

148151

149152
def negList(ls: Iterable[float]) -> Iterable[float]:
150153
"Use `map` and `neg` to negate each element in `ls`"
151-
# TODO: Implement for Task 0.3.
152-
raise NotImplementedError("Need to implement for Task 0.3")
154+
return map(lambda x: -x)(ls)
153155

154156

155157
def zipWith(
@@ -168,14 +170,16 @@ def zipWith(
168170
applying fn(x, y) on each pair of elements.
169171
170172
"""
171-
# TODO: Implement for Task 0.3.
172-
raise NotImplementedError("Need to implement for Task 0.3")
173+
174+
def new_fn(ls1: Iterable[float], ls2: Iterable[float]) -> Iterable[float]:
175+
return [fn(ls1[i], ls2[i]) for i in range(len(ls1))]
176+
177+
return new_fn
173178

174179

175180
def addLists(ls1: Iterable[float], ls2: Iterable[float]) -> Iterable[float]:
176181
"Add the elements of `ls1` and `ls2` using `zipWith` and `add`"
177-
# TODO: Implement for Task 0.3.
178-
raise NotImplementedError("Need to implement for Task 0.3")
182+
return zipWith(add)(ls1, ls2)
179183

180184

181185
def reduce(

tests/test_operators.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Callable, List, Tuple
1+
from typing import Callable, List, Tuple, Iterable
22

33
import pytest
44
from hypothesis import given
@@ -15,6 +15,7 @@
1515
log_back,
1616
lt,
1717
max,
18+
map,
1819
mul,
1920
neg,
2021
negList,
@@ -162,6 +163,22 @@ def test_other(a: float, b: float, c: float) -> None:
162163
# properties.
163164

164165

166+
@pytest.mark.task0_3
167+
@given(lists(small_floats, min_size=0, max_size=100), small_floats)
168+
def test_map(ls: Iterable[float], a: float) -> None:
169+
def fn(x: float) -> float:
170+
return x + a
171+
172+
def fn2(x: float) -> float:
173+
return x * a
174+
175+
expected1 = [fn(x) for x in ls]
176+
expected2 = [fn2(x) for x in ls]
177+
178+
assert expected1 == map(fn)(ls)
179+
assert expected2 == map(fn2)(ls)
180+
181+
165182
@pytest.mark.task0_3
166183
@given(small_floats, small_floats, small_floats, small_floats)
167184
def test_zip_with(a: float, b: float, c: float, d: float) -> None:

0 commit comments

Comments
 (0)