Code exercise gallery
A fixture, not a lesson. Every exercise state is exercised here so a regression in the Python runtime shows up in one place.
Python runs entirely in your browser through Pyodide. The runtime is about 10 MB and downloads once, on the first Run or Check, never on page load.
1. Complete the function
Section titled “1. Complete the function”Cooperative reward
Implement the reward from the Coordinate chapter, then use Check to test it against all four joint actions.
def team_reward(a, b):
"""Return +1 when the channels differ, -1 when they collide."""
# TODO: replace this with the reward rule
return 0
Output
Hints
- There are only two cases: the channels are equal, or they are not.
- A conditional expression works in one line: `return 1 if a != b else -1`.
One solution
def team_reward(a, b):
return 1 if a != b else -1
Other correct answers exist. The checks test behaviour, not wording.
2. Implement the equation
Section titled “2. Implement the equation”Jain's fairness index
The fairness metric used throughout the wireless lab.
def jain(rates):
"""J = (sum x)^2 / (n * sum x^2)"""
# TODO
return 0.0
Output
Hints
- Sum the rates once, and sum their squares once.
- n is the number of rates. Watch the denominator: it is n times the sum of squares.
One solution
def jain(rates):
total = sum(rates)
squares = sum(x * x for x in rates)
n = len(rates)
if squares == 0:
return 1.0
return (total * total) / (n * squares)
Other correct answers exist. The checks test behaviour, not wording.
3. Failure states
Section titled “3. Failure states”An exercise whose starter code raises, so the error path is visible: the checks should not run at all, and the traceback should mention only the learner’s own code.
Deliberately broken starter
Press Check. The runtime should report that the code raised before the checks could run, rather than listing failed assertions.
def add(a, b):
return a + undefined_name
Output
One solution
def add(a, b):
return a + b
Other correct answers exist. The checks test behaviour, not wording.