Fenrir, the great wolf, prowls the only road through Ironwood, and no binding with a flaw can hold him. The gods once bound him with Gleipnir, a ribbon of runes the dwarves made from six things that do not exist. When you caught Loki, Fenrir's father, the wolf tore it in fury, and its broken runes fused into him. Weave Gleipnir again, strand by strand: counted, tied off and tested. Your code is your binding. Every stage you win pulls it tighter; every run that fails lets him pounce.
The fight
Four stages, each building on the last. Every stage opens with a finished version of the code from the stage before, so you pick up where you left off. This fight draws on generators, itertools, decorators, context managers, namedtuple and unittest.
Stage 1: The strands. Draw the strands out one at a time, only as you need them.
Stage 2: The count. Count every weave with a decorator.
Stage 3: The knot. Loop the binding round him and tie it off, whatever happens.
Stage 4: The test. Test the binding before he does.
The fight
0 of 4 stages won
Stage 1 of 4
+60 XP
Draw the strands out one at a time. They lie where he tore free: the sound of a cat's footfall, the beard of a woman, the roots of a mountain, the sinews of a bear, the breath of a fish and the spittle of a bird. Take only as many as you need: pull the whole ribbon at once and he sees it coming. GLEIPNIR holds the six strands. Write a generator function strands() that yields them one at a time, in order, and take(n, iterable), which returns a list of the first n items of any iterable using islice, without reading any further than it needs to. Give both functions type hints for their parameters and return values (Iterator[str] from collections.abc suits a generator). For example, take(2, strands()) is ["the sound of a cat's footfall", 'the beard of a woman'].
GLEIPNIR = (
"the sound of a cat's footfall",
'the beard of a woman',
'the roots of a mountain',
'the sinews of a bear',
'the breath of a fish',
'the spittle of a bird',
)
from collections.abc import Iterable, Iterator
from itertools import islice
def strands():
# Yield each strand of GLEIPNIR in turn (and add type hints)
pass
def take(n, iterable):
# The first n items, as a list, reading no further than needed
pass
Ctrl + Enter to run
Run your code to check it against the tests.
Stage 2 of 4
+60 XP
Count every weave. He picks apart any knot you lose count of. Keep stage 1. Write a decorator counted that counts how many times the decorated function is called, in an attribute calls on the wrapper that starts at 0. The wrapper passes any positional and keyword arguments through, returns the function's result, and uses functools.wraps so it keeps the function's name and docstring. Then write weave(n: int) -> list[str], with a docstring, decorated with @counted, returning the first n strands by way of take and strands. For example, after two more calls to weave, weave.calls has gone up by 2.
GLEIPNIR = (
"the sound of a cat's footfall",
'the beard of a woman',
'the roots of a mountain',
'the sinews of a bear',
'the breath of a fish',
'the spittle of a bird',
)
from collections.abc import Iterable, Iterator
from itertools import islice
def strands() -> Iterator[str]:
for strand in GLEIPNIR:
yield strand
def take(n: int, iterable: Iterable) -> list:
return list(islice(iterable, n))
from functools import wraps
def counted(func):
# Wrap func, count its calls in wrapper.calls, keep its name and docstring
pass
# Decorate weave with @counted and give it a docstring
def weave(n: int) -> list[str]:
pass
Ctrl + Enter to run
Run your code to check it against the tests.
Stage 3 of 4
+60 XP
Tie it off, whatever happens. Even when he bites, the knot gets tied, and the bite still gets through to you. Keep everything and write a context manager binding(log) with contextlib.contextmanager. On entry it appends 'bound' to the list log; on exit it appends 'knotted', even when the body of the with block raises an error of any kind. It works like with open(...): set up before yield and clean up after it. But a plain line after yield is skipped when the body raises, so make sure the clean-up runs anyway. The exception must still reach the caller: the knot is the clean-up; it doesn't swallow the bite. strain(log, bite=False) is already written for you (leave it as it is): it appends 'strain' inside with binding(log):, then raises RuntimeError if bite is true. So strain(log) leaves log as ['bound', 'strain', 'knotted'], and strain(log, bite=True) raises and still leaves it as ['bound', 'strain', 'knotted'].
GLEIPNIR = (
"the sound of a cat's footfall",
'the beard of a woman',
'the roots of a mountain',
'the sinews of a bear',
'the breath of a fish',
'the spittle of a bird',
)
from collections.abc import Iterable, Iterator
from itertools import islice
def strands() -> Iterator[str]:
for strand in GLEIPNIR:
yield strand
def take(n: int, iterable: Iterable) -> list:
return list(islice(iterable, n))
from functools import wraps
def counted(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@counted
Ctrl + Enter to run
Run your code to check it against the tests.
Stage 4 of 4
+60 XP
Measure the strands, then test the binding. He tries every knot for a weak one, so find yours first. Keep everything. Define Strand = namedtuple('Strand', 'name length') and write strand_lengths(), which returns a list with a Strand for each strand of Gleipnir, where length is the number of words in it. Then write a unittest.TestCase subclass GleipnirTests with at least three test methods: one that checks weave(3) returns three strands, one that checks weave.calls goes up when weave is called, and one that checks binding logs 'knotted' after the body raises. weave.calls doesn't start from 0 in your test, because anything that calls weave adds to it: save it, call weave, and check it went up. Finally, write run_tests(), which runs GleipnirTests with unittest.TextTestRunner(stream=io.StringIO()) and returns whether they all passed. For example, strand_lengths()[1] is Strand('the beard of a woman', 5).
GLEIPNIR = (
"the sound of a cat's footfall",
'the beard of a woman',
'the roots of a mountain',
'the sinews of a bear',
'the breath of a fish',
'the spittle of a bird',
)
from collections.abc import Iterable, Iterator
from itertools import islice
def strands() -> Iterator[str]:
for strand in GLEIPNIR:
yield strand
def take(n: int, iterable: Iterable) -> list:
return list(islice(iterable, n))
from functools import wraps
def counted(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@counted