CPSC 203, 2025 W2
January 27, 2026
A dataclass bundles related data together into a custom type.
radius, colour)diameter)What data describes a bead?
What data describes a bracelet?
A bracelet contains a list of beads and has a radius.
This is composition: a Bracelet contains Beads.
The beads fit on the bracelet if the sum of their diameters is less than or equal to the circumference. We refer to the extra string as slack.
We only want to add a bead if it fits!
What if we want to swap out a bead?
Hint: Lists have a method called pop(index) that removes and returns the item at that index.
@dataclass
class Bead:
radius: float
colour: tuple[int, int, int]
def diameter(self) -> float: ...
def draw(self, ax, x: float, y: float) -> None: ...
@dataclass
class Bracelet:
radius: float
beads: list[Bead]
def circumference(self) -> float: ...
def slack(self) -> float: ...
def string_bead(self, bead: Bead) -> bool: ...
def remove_bead(self, index: int) -> Bead: ...
def draw(self) -> None: ...Try the Bracelet Activity on PrairieLearn!
Implement these methods:
circumference() - return 2πrslack() - circumference minus total bead diametersstring_bead(bead) - add bead if it fits, return True/Falseremove_bead(index) - remove and return the bead at indexIf you finish early, try Tasks 4 & 5 (brighten methods)!
30:00
What if we want to make a friendship bracelet with someone’s name on it?
We need beads that can hold letters!
Let’s add an optional letter attribute to our Bead class:
Now beads can optionally have letters!
enumerate() functionWhen iterating over a list, sometimes you need both the index and the value:
enumerate() gives you pairs of (index, value) as you loop.
Add a name() method to Bracelet that assigns letters to existing beads:
Why reversed? So the name reads correctly around the circle!
name()Back to PrairieLearn - try Task 6: Letter Beads!
15:00
Identify the objects in your problem (nouns)
List the data each object needs (attributes)
List the operations each object supports (methods)
Decide which object is responsible for what
Implement and test incrementally