-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathtest_11_functional_programming.py
More file actions
256 lines (189 loc) · 5.81 KB
/
test_11_functional_programming.py
File metadata and controls
256 lines (189 loc) · 5.81 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import ast
import functools
import inspect
import itertools
import random
from collections.abc import Callable
from typing import Any
import numpy as np
import pytest
import requests
from numpy.typing import NDArray
#
# Example: Pure Function
#
def reference_pure_function(array, new_element):
return array + [new_element]
@pytest.mark.parametrize(
"array, new_element",
[
([1, 2, 3], 4),
(["cat", "dog"], "bird"),
],
)
def test_pure_function(array, new_element, function_to_test):
output_array = function_to_test(array, new_element)
assert id(output_array) != id(array), "The arrays must be different objects."
assert output_array == reference_pure_function(array, new_element)
#
# Example: Composition
#
def reference_composition(x, y):
def square(x: int) -> int:
return x * x
def add(x: int, y: int) -> int:
return x + y
def eq(x: int, y: int) -> int:
return add(square(x), square(y))
return eq(x, y)
@pytest.mark.parametrize(
"x, y",
[
(2, 4),
(5, 10),
],
)
def test_composition(x, y, function_to_test):
assert function_to_test(x, y) == reference_composition(x, y)
#
# Example: Filter Even Numbers
#
def check_for_loop_in_body(fun: Callable) -> bool:
"""Checks if the body of a function contains a for loop"""
tree = ast.parse(inspect.getsource(fun))
for node in ast.walk(tree):
if isinstance(node, ast.For):
return True
return False
def reference_filter_even(my_list: list[int]) -> list[int]:
return list(filter(lambda x: x % 2 == 0, my_list))
@pytest.mark.parametrize(
"my_list",
[
([1, 2, 3, 4]),
(list(range(100, 2))),
([random.randint(0, 10) for i in range(100)]),
],
)
def test_filter_even(function_to_test: Callable, my_list: list[int]):
res = function_to_test(my_list)
assert isinstance(res, list), "The function you wrote does not return a list"
assert not check_for_loop_in_body(function_to_test), (
"You are not allowed to use a for loop in this exercise"
)
assert res == reference_filter_even(my_list), (
"The list you return is not equal to the expected solution"
)
#
# Example: Add 1 to Each Element
#
def reference_add_one(my_list: list[int]) -> list[int]:
return list(map(lambda x: x + 1, my_list)) # noqa: C417
@pytest.mark.parametrize(
"my_list",
[
([1, 2, 3, 4]),
(list(range(100, 2))),
([random.randint(0, 10) for i in range(100)]),
],
)
def test_add_one(function_to_test: Callable, my_list: list[int]):
assert function_to_test(my_list) == reference_add_one(my_list), (
"The list you return is not equal to the expected solution"
)
assert not check_for_loop_in_body(function_to_test), (
"You are not allowed to use a for loop in this exercise"
)
#
# Example: Keeping only multiples of n
#
def reference_multiples_of_n(my_list: list[int], k: int) -> list[int]:
return [i for i in my_list if i % k == 0]
@pytest.mark.parametrize(
"my_list, k",
[
([1, 2, 3, 4], 1),
(list(range(100)), 5),
],
)
def test_multiples_of_n(
function_to_test: Callable[[list[int], int], int],
my_list: list[int],
k: int,
):
assert function_to_test(my_list, k) == reference_multiples_of_n(my_list, k)
#
# Exercise 1: Transposing a Matrix
#
def reference_exercise1(matrix: list[list[int]]) -> list[list[int]]:
return [list(i) for i in zip(*matrix, strict=False)]
@pytest.mark.parametrize(
"my_input",
[(np.eye(3)), (np.random.randint(0, 100, size=(4, 4)))],
)
def test_exercise1(
function_to_test: Callable[[list[list[int]]], list[list[int]]],
my_input: NDArray,
):
res = function_to_test(my_input.tolist())
assert (
res == reference_exercise1(my_input.tolist())
and res == my_input.transpose().tolist()
)
#
# Exercise 2: Flattening list of lists
#
def reference_exercise2(my_list: list[list[Any]]) -> list[Any]:
return functools.reduce(lambda x, y: x + y, my_list)
@pytest.mark.parametrize(
"my_input",
[
[[1, 2, 3, 4], [4, 5, 5], [4, 5, 6]],
[["a", "b", "c"], ["d", "f", "e"], ["another"]],
],
)
def test_exercise2(
function_to_test: Callable[[list[list[Any]]], list[Any]],
my_input: list[list[Any]],
):
assert function_to_test(my_input) == reference_exercise2(my_input)
#
# Exercise 3: Counting initials
#
@functools.lru_cache
def get_data_exercise3() -> list[str]:
words = requests.get("https://www.mit.edu/~ecprice/wordlist.10000").text
return words.splitlines()
def reference_exercise3(words: list[str]) -> list[tuple[str, int]]:
return [
(k, len(list(v)))
for k, v in itertools.groupby(
sorted(words, key=lambda x: x.lower()[0]), key=lambda x: x.lower()[0]
)
]
def test_exercise3(
function_to_test: Callable[[list[str]], list[tuple[str, int]]],
):
data = get_data_exercise3()
assert function_to_test(data) == reference_exercise3(data)
#
# Exercise 4: Counting initials frequency
#
def reference_exercise4(
my_list: list[tuple[str, int]],
) -> list[tuple[str, float]]:
total = sum(map(lambda x: x[1], my_list)) # noqa: C417
return [(letter, freq / total) for letter, freq in my_list]
def test_exercise4(
function_to_test: Callable[[list[tuple[str, int]]], list[tuple[str, float]]],
):
input_data = reference_exercise3(get_data_exercise3())
assert function_to_test(input_data) == reference_exercise4(input_data)
#
# Exercise 5: Finding palindromes
#
def reference_exercise5(words: list[str]) -> list[str]:
return list(filter(lambda x: len(x) > 1 and x == x[::-1], words))
def test_exercise5(function_to_test: Callable[[list[str]], list[str]]):
data = get_data_exercise3()
assert function_to_test(data) == reference_exercise5(data)