-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtest_03_functions.py
More file actions
415 lines (324 loc) · 11.6 KB
/
test_03_functions.py
File metadata and controls
415 lines (324 loc) · 11.6 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import inspect
import pathlib
from collections import Counter
from string import ascii_lowercase, ascii_uppercase
from typing import Any
import pytest
def read_data(name: str, data_dir: str = "data") -> pathlib.Path:
"""Read input data"""
return (pathlib.Path(__file__).parent / f"{data_dir}/{name}").resolve()
#
# Exercise 1: a `greet` function
#
def reference_greet(name: str, age: int) -> str:
"""Creates a personalized greeting message using name and age.
Args:
name: The person's name to include in the greeting
age: The person's age in years
Returns:
- A string in the format "Hello, <name>! You are <age> years old."
"""
return f"Hello, {name}! You are {age} years old."
def test_greet(
function_to_test,
) -> None:
name, age = "Alice", 30
params = inspect.signature(function_to_test).parameters
return_annotation = inspect.signature(function_to_test).return_annotation
# Check docstring
assert function_to_test.__doc__ is not None, "The function is missing a docstring."
# Check number and names of parameters
assert len(params) == 2, "The function should take two arguments."
assert "name" in params and "age" in params, (
"The function's parameters should be 'name' and 'age'."
)
# Check type hints for parameters
assert all(p.annotation != inspect.Parameter.empty for p in params.values()), (
"The function's parameters should have type hints."
)
# Check return type hint
assert return_annotation != inspect.Signature.empty, (
"The function's return value is missing the type hint."
)
# Test the return value
assert function_to_test(name, age) == reference_greet(name, age)
#
# Exercise 2: calculate area with units
#
# Part 1
def reference_calculate_basic_area(length: float, width: float) -> str:
"""Reference solution for Part 1: basic area calculation."""
area = round(length * width, 2)
return f"{area} cm^2"
def validate_basic_area_signature(function_to_test) -> None:
"""Validate signature of the basic area calculation function."""
signature = inspect.signature(function_to_test)
params = signature.parameters
return_annotation = signature.return_annotation
assert function_to_test.__doc__ is not None, "The function is missing a docstring."
assert len(params) == 2, (
"The function should take exactly two arguments (length and width)."
)
assert all(p in params.keys() for p in ["length", "width"]), (
"The function's parameters should be 'length' and 'width'."
)
assert all(p.annotation is float for p in params.values()), (
"Both parameters should be annotated as float."
)
assert return_annotation is str, "The return type should be annotated as str."
@pytest.mark.parametrize(
"length,width",
[
(2.0, 3.0),
(5.0, 4.0),
(1.5, 2.5),
(0.1, 0.1),
],
)
def test_calculate_basic_area(length: float, width: float, function_to_test):
validate_basic_area_signature(function_to_test)
expected = reference_calculate_basic_area(length, width)
result = function_to_test(length, width)
assert isinstance(result, str), "Result should be a string"
assert expected == result, "Incorrect area calculation or formatting"
# Part 2
def reference_calculate_metric_area(
length: float, width: float, unit: str = "cm"
) -> str:
"""Reference solution for Part 2: metric units only."""
if unit not in ("cm", "m"):
return f"Invalid unit: {unit}"
if unit == "m":
length *= 100
width *= 100
area = round(length * width, 2)
return f"{area} cm^2"
def validate_metric_area_signature(function_to_test) -> None:
"""Validate signature of the metric area calculation function."""
signature = inspect.signature(function_to_test)
params = signature.parameters
return_annotation = signature.return_annotation
assert function_to_test.__doc__ is not None, "The function is missing a docstring."
assert len(params) == 3, (
"The function should take three arguments (length, width, and unit)."
)
assert all(p in params.keys() for p in ["length", "width", "unit"]), (
"The function's parameters should be 'length', 'width' and 'unit'."
)
assert params["length"].annotation is float, (
"Parameter 'length' should be annotated as float."
)
assert params["width"].annotation is float, (
"Parameter 'width' should be annotated as float."
)
assert params["unit"].annotation is str, (
"Parameter 'unit' should be annotated as str."
)
assert params["unit"].default == "cm", (
"Parameter 'unit' should have a default value of 'cm'."
)
assert return_annotation is str, "The return type should be annotated as str."
@pytest.mark.parametrize(
"length,width,unit",
[
(2.0, 3.0, "cm"),
(2.0, 3.0, "m"),
(1.5, 2.0, "cm"),
(1.5, 2.0, "m"),
],
)
def test_calculate_metric_area(length, width, unit, function_to_test):
validate_metric_area_signature(function_to_test)
expected = reference_calculate_metric_area(length, width, unit)
result = function_to_test(length, width, unit)
assert isinstance(result, str), "Result should be a string"
assert expected == result, "Incorrect area calculation or formatting"
# Part 3
def reference_calculate_area(length: float, width: float, unit: str = "cm") -> str:
"""Reference solution for Part 3: all units."""
conversions = {"cm": 1, "m": 100, "mm": 0.1, "yd": 91.44, "ft": 30.48}
try:
factor = conversions[unit]
except KeyError:
return f"Invalid unit: {unit}"
area = round(length * width * factor**2, 2)
return f"{area} cm^2"
def validate_area_signature(function_to_test) -> None:
"""Validate signature of the full area calculation function."""
signature = inspect.signature(function_to_test)
params = signature.parameters
return_annotation = signature.return_annotation
assert function_to_test.__doc__ is not None, "The function is missing a docstring."
assert len(params) == 3, (
"The function should take three arguments (length, width, and unit)."
)
assert all(p in params.keys() for p in ["length", "width", "unit"]), (
"The function's parameters should be 'length', 'width' and 'unit'."
)
assert params["length"].annotation is float, (
"Parameter 'length' should be annotated as float."
)
assert params["width"].annotation is float, (
"Parameter 'width' should be annotated as float."
)
assert params["unit"].annotation is str, (
"Parameter 'unit' should be annotated as str."
)
assert params["unit"].default == "cm", (
"Parameter 'unit' should have a default value of 'cm'."
)
assert return_annotation is str, "The return type should be annotated as str."
@pytest.mark.parametrize(
"length,width,unit",
[
(2.0, 3.0, "cm"),
(2.0, 3.0, "m"),
(2.0, 3.0, "mm"),
(2.0, 3.0, "yd"),
(2.0, 3.0, "ft"),
],
)
def test_calculate_area(length, width, unit, function_to_test):
validate_area_signature(function_to_test)
result = function_to_test(length, width, unit)
expected = reference_calculate_area(length, width, unit)
assert isinstance(result, str), "Result should be a string"
assert expected == result, "Incorrect area calculation or formatting"
#
# Exercise 3: summing anything
#
def reference_combine_anything(*args: Any) -> Any:
"""Reference solution for the combine_anything exercise"""
if not args:
return args
result = args[0]
for item in args[1:]:
result += item
return result
@pytest.mark.parametrize(
"args",
[
(()),
((1, 2, 3)),
(([1, 2, 3], [4, 5, 6])),
(("hello", "world")),
],
)
def test_combine_anything(args: Any, function_to_test) -> None:
assert function_to_test(*args) == reference_combine_anything(*args)
#
# Exercise: Longest Sequence
#
def reference_longest_sequence(nums: list[int]) -> int:
"""
Find the longest consecutive sequence of integers
This is the best solution achievable: O(n)
"""
longest = 0
nums_set = set(nums)
for num in nums_set:
if num - 1 not in nums_set:
cur = num
cur_streak = 1
while cur + 1 in nums_set:
cur += 1
cur_streak += 1
longest = max(longest, cur_streak)
return longest
@pytest.mark.parametrize(
"input_nums",
[
[100, 4, 200, 1, 3, 2],
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1],
[0, 2, 14, 12, 4, 18, 16, 8, 10, 6],
],
)
def test_longest_sequence(input_nums: list[int], function_to_test) -> None:
assert function_to_test(input_nums) == reference_longest_sequence(input_nums)
@pytest.mark.timeout(60)
@pytest.mark.parametrize(
"input_nums",
[
[int(x) for x in read_data("longest_10000.txt").read_text().splitlines()],
],
)
def test_longest_sequence_best(input_nums: list[int], function_to_test) -> None:
assert function_to_test(input_nums) == reference_longest_sequence(input_nums)
#
# Exercise: Password Validator
#
def reference_password_validator1(start: int, end: int) -> int:
"""Password validator reference solution (part 1)"""
count = 0
for pwd in range(start, end + 1):
pwd = list(str(pwd))
if pwd == sorted(pwd) and len(pwd) != len(set(pwd)):
count += 1
return count
def reference_password_validator2(start: int, end: int) -> int:
"""Password validator reference solution (part 2)"""
count = 0
for pwd in range(start, end + 1):
pwd = list(str(pwd))
if pwd == sorted(pwd):
counter = Counter(pwd).values()
if list(counter).count(2) >= 1:
count += 1
return count
@pytest.mark.parametrize(
"start,end",
[
(138241, 674034),
(136760, 595730),
],
)
def test_password_validator1(start: int, end: int, function_to_test) -> None:
assert function_to_test(start, end) == reference_password_validator1(start, end)
@pytest.mark.parametrize(
"start,end",
[
(138241, 674034),
(136760, 595730),
],
)
def test_password_validator2(start: int, end: int, function_to_test) -> None:
assert function_to_test(start, end) == reference_password_validator2(start, end)
#
# Exercise: Buckets reorganization
#
prio = {
letter: i for i, letter in enumerate(ascii_lowercase + ascii_uppercase, start=1)
}
buckets_1, buckets_2 = (read_data(f"buckets_{num}.txt") for num in (1, 2))
def reference_buckets1(buckets: pathlib.Path) -> int:
"""Reference solution (part 1)"""
data = buckets.read_text().splitlines()
total = 0
for line in data:
mid = len(line) // 2
first, second = set(line[:mid]), set(line[mid:])
common = (first & second).pop()
total += prio[common]
return total
def reference_buckets2(buckets: pathlib.Path) -> int:
"""Reference solution (part 2)"""
data = buckets.read_text().splitlines()
total = 0
i = 0
for line in data[::3]:
group = set(line) & set(data[i + 1]) & set(data[i + 2])
total += prio[group.pop()]
i += 3
return total
@pytest.mark.parametrize(
"buckets",
[buckets_1, buckets_2],
)
def test_buckets1(buckets: pathlib.Path, function_to_test):
assert function_to_test(buckets) == reference_buckets1(buckets)
@pytest.mark.parametrize(
"buckets",
[buckets_1, buckets_2],
)
def test_buckets2(buckets: pathlib.Path, function_to_test):
assert function_to_test(buckets) == reference_buckets2(buckets)