Skip to content

Commit ea7847b

Browse files
authored
Fix errors in Advanced Functions notebook (#320)
* Fix datetime.UTC issue * Fix test to randomize with lambda
1 parent 68a43da commit ea7847b

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

12_functions_advanced.ipynb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -335,10 +335,10 @@
335335
"metadata": {},
336336
"outputs": [],
337337
"source": [
338-
"from datetime import datetime\n",
338+
"from datetime import datetime, UTC\n",
339339
"\n",
340340
"\n",
341-
"def log(msg, *, dt=datetime.utcnow()):\n",
341+
"def log(msg, *, dt=datetime.now(UTC)):\n",
342342
" print(f\"{dt}: {msg}\")"
343343
]
344344
},
@@ -362,9 +362,9 @@
362362
"source": [
363363
"from time import sleep\n",
364364
"\n",
365-
"log(\"my first message\")\n",
365+
"log(\"A first message\")\n",
366366
"sleep(5)\n",
367-
"log(\"my first message\")"
367+
"log(\"A second message\")"
368368
]
369369
},
370370
{
@@ -395,7 +395,7 @@
395395
"outputs": [],
396396
"source": [
397397
"def log(msg, *, dt=None):\n",
398-
" dt = dt or datetime.now(datetime.timezone.utc)\n",
398+
" dt = dt or datetime.now(UTC)\n",
399399
" print(f\"{dt}: {msg}\")"
400400
]
401401
},
@@ -408,9 +408,9 @@
408408
},
409409
"outputs": [],
410410
"source": [
411-
"log(\"my first message\")\n",
411+
"log(\"A first message\")\n",
412412
"sleep(5)\n",
413-
"log(\"my first message\")"
413+
"log(\"A second message\")"
414414
]
415415
},
416416
{

tutorial/tests/test_12_functions_advanced.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,31 @@ def test_randomize_list(
2929
function_to_test: t.Callable,
3030
my_list: list[int],
3131
):
32-
assert function_to_test(my_list) == reference_randomize_list(my_list)
32+
# Skip randomization tests for trivial lists
33+
if len(my_list) <= 1:
34+
return
35+
36+
# Run the function multiple times to ensure randomization
37+
results = []
38+
for _ in range(10): # Run multiple times
39+
# Use a copy to prevent the function from modifying the original
40+
test_list = my_list.copy()
41+
result = function_to_test(test_list)
42+
43+
# Check that the elements are preserved
44+
assert sorted(result) == sorted(my_list)
45+
46+
results.append(result)
47+
48+
# For lists with enough elements, very unlikely to get the same result twice
49+
# 1. Convert each of the results to tuples
50+
# 2. {tuple(r) for r in results} create a set that deduplicates identical orderings
51+
# 3. len(...) > 1 checks that we've seen at least two different orderings
52+
if len(my_list) > 2:
53+
# Check there's at least some variation in results
54+
assert len({tuple(r) for r in results}) > 1, (
55+
"Your function doesn't appear to randomize. You should not use random.seed()."
56+
)
3357

3458

3559
#

0 commit comments

Comments
 (0)