Robot Name2026-04-21
My Solution: Exercism Robot Name solution
Instructions
Manage a robot factory where each robot gets a unique name made of two uppercase letters followed by three digits, like RX837.
Rules:
- A robot should lazily generate its name the first time
nameis requested. - The generated name should stay the same for that robot until
reset()is called. reset()should clear the robot's current name so that the next access tonamegenerates a fresh one.- Generated names should not be reused.
Solution
import random
import string
class Robot:
_used_names = set()
def __init__(self):
self._name = None
@property
def name(self):
if not self._name:
self._name = self._generate_name()
return self._name
def _generate_name(self):
while True:
letters = "".join(random.choices(string.ascii_uppercase, k=2))
digits = "".join(random.choices(string.digits, k=3))
new_name = letters + digits
if new_name not in Robot._used_names:
Robot._used_names.add(new_name)
return new_name
def reset(self):
self._name = None
Syntax Notes
- A leading underscore in
_nameand_generate_namesignals internal/private-by-convention members. - The
@propertydecorator letsnamebe accessed like an attribute (robot.name) while still running method logic. _used_namesis a class attribute, shared across all robot instances to enforce global uniqueness.