Coding Challenges: OOP Deeper
8 HackerRank-style challenges, auto-graded right in your browser —
no setup required. Write your function in the code box, then click
Run Tests to check it against a set of test cases
(including edge cases). Stuck? Every challenge has a
Show Solution reveal at the bottom. Only uses what
Chapters 1-15 have covered so far — including
@staticmethod, @classmethod alternative
constructors, and @property getters/setters with
validation. No inheritance, or any import beyond
math/datetime/random/csv.
Circle with a @property
area, a BankAccount with a validated
balance setter, and so on), but the function itself always
returns a plain number, string, boolean, list, or dict — exactly
what a real caller elsewhere in a program would want back, without
needing to know anything about the class you used internally to
compute it.
1 Circle Measurements Easy
Write a function circle_measurements(radius) that builds a Circle class internally with __init__(self, radius) storing self.radius = radius, a @property area(self) returning round(3.14159 * self.radius ** 2, 2), and a @staticmethod unit_circle_area() returning round(3.14159, 2) (the area of a circle with radius 1, a fixed fact that doesn't depend on any instance). Create one instance and return {"area": circle.area, "unit_area": Circle.unit_circle_area()}.
radius is a non-negative number, including 0.
circle_measurements(4) → {"area": 50.27, "unit_area": 3.14}circle_measurements(0) → {"area": 0.0, "unit_area": 3.14}
Show Solution
def circle_measurements(radius):
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
@staticmethod
def unit_circle_area():
return round(3.14159, 2)
circle = Circle(radius)
return {"area": circle.area, "unit_area": Circle.unit_circle_area()}
2 Build a Square Easy
Write a function square_from_side(side_length) that builds a Rectangle class internally with __init__(self, width, height), a @classmethod square(cls, side_length) returning cls(side_length, side_length), and an area(self) method returning self.width * self.height. Create square = Rectangle.square(side_length) and return square.area().
side_length is a non-negative integer, including 0.
square_from_side(5) → 25square_from_side(0) → 0
Show Solution
def square_from_side(side_length):
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@classmethod
def square(cls, side_length):
return cls(side_length, side_length)
def area(self):
return self.width * self.height
square = Rectangle.square(side_length)
return square.area()
3 Parse a Date String Easy
Write a function parse_date_parts(date_string) that builds a Date class internally with __init__(self, year, month, day) storing all three, and a @classmethod from_string(cls, date_string) that splits date_string on "-" (format "YYYY-MM-DD"), converts each piece to int, and returns cls(year, month, day). Create date = Date.from_string(date_string) and return [date.year, date.month, date.day].
date_string is always a valid "YYYY-MM-DD" string.
parse_date_parts("2026-07-04") → [2026, 7, 4]parse_date_parts("2000-01-01") → [2000, 1, 1]
Show Solution
def parse_date_parts(date_string):
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_string):
year, month, day = date_string.split("-")
return cls(int(year), int(month), int(day))
date = Date.from_string(date_string)
return [date.year, date.month, date.day]
4 Validated Price Assignment Medium
Write a function try_set_price(price) that builds a Product class internally with __init__(self, name, price) that calls self.price = price (through the setter), a @property getter price(self) returning self._price, and a @price.setter price(self, value) that raises ValueError("price cannot be negative") if value < 0, otherwise sets self._price = value. Try creating Product("Widget", price) inside a try/except ValueError block: if it succeeds, return {"ok": True, "price": product.price}; if it raises, return {"ok": False, "error": str(error)}.
price may be positive, negative, or zero.
try_set_price(9.99) → {"ok": true, "price": 9.99}try_set_price(-5) → {"ok": false, "error": "price cannot be negative"}
Show Solution
def try_set_price(price):
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self._price = value
try:
product = Product("Widget", price)
return {"ok": True, "price": product.price}
except ValueError as error:
return {"ok": False, "error": str(error)}
5 Bank Account With Guarded Withdrawals Medium
Write a function run_account_operations(starting_balance, operations) that builds a BankAccount class internally with a validated balance @property (getter returns self._balance; setter raises ValueError("balance cannot be negative") if value < 0, otherwise sets it), plus deposit(self, amount) and withdraw(self, amount) methods that both assign back through self.balance = ... so the setter's validation applies to every operation. Create one instance with starting_balance, then apply every [op, amount] pair in operations in order inside a try/except ValueError that skips (does not apply) any operation that would make the balance negative, counting how many were skipped. Return {"balance": account.balance, "rejected": <count skipped>}.
operations may be empty; a rejected withdrawal leaves the balance unchanged and does not stop later operations from being tried.
run_account_operations(100, [["deposit", 50], ["withdraw", 30]]) → {"balance": 120, "rejected": 0}run_account_operations(100, [["withdraw", 500]]) → {"balance": 100, "rejected": 1}
Show Solution
def run_account_operations(starting_balance, operations):
class BankAccount:
def __init__(self, balance):
self.balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
def deposit(self, amount):
self.balance = self.balance + amount
def withdraw(self, amount):
self.balance = self.balance - amount
account = BankAccount(starting_balance)
rejected = 0
for op, amount in operations:
try:
if op == "deposit":
account.deposit(amount)
elif op == "withdraw":
account.withdraw(amount)
except ValueError:
rejected += 1
return {"balance": account.balance, "rejected": rejected}
6 Auto-Incrementing Employee Ids Medium
Write a function hire_employees(names) that builds an Employee class internally with a private class attribute __next_id = 1, __init__(self, name, salary) that stores self.name, calls self.salary = salary (through the setter), sets self.id = Employee.__next_id, then increments Employee.__next_id by 1, plus a validated salary @property (setter raises ValueError("salary cannot be negative") if value < 0) and a @classmethod entry_level(cls, name) returning cls(name, 45000). Create one employee per name in names using Employee.entry_level(name), in order, and return a list of [employee.id, employee.salary] pairs.
names may be empty, in which case return an empty list; ids always start at 1 for each call.
hire_employees(["Priya", "Sam"]) → [[1, 45000], [2, 45000]]hire_employees([]) → []
Show Solution
def hire_employees(names):
class Employee:
__next_id = 1
def __init__(self, name, salary):
self.name = name
self.salary = salary
self.id = Employee.__next_id
Employee.__next_id += 1
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
raise ValueError("salary cannot be negative")
self._salary = value
@classmethod
def entry_level(cls, name):
return cls(name, 45000)
employees = [Employee.entry_level(name) for name in names]
return [[employee.id, employee.salary] for employee in employees]
7 With vs. Without Validation Medium
Write a function compare_validation(value) that defines two classes internally: an UnsafeAccount with a plain __init__(self, balance) storing self.balance = balance with no checks at all, and a SafeAccount with __init__(self, balance) that calls self.balance = balance through a validated @property setter raising ValueError("balance cannot be negative") if value < 0. Create an UnsafeAccount(value) and read its .balance directly. Then, inside a try/except ValueError, create a SafeAccount(value) and read its .balance if it succeeds, or capture str(error) if it raises. Return {"unsafe": <unsafe balance>, "safe": <safe balance or error message>} — demonstrating exactly what a missing validation layer lets slip through.
value may be positive, negative, or zero.
compare_validation(100) → {"unsafe": 100, "safe": 100}compare_validation(-50) → {"unsafe": -50, "safe": "balance cannot be negative"}
Show Solution
def compare_validation(value):
class UnsafeAccount:
def __init__(self, balance):
self.balance = balance # no validation at all
class SafeAccount:
def __init__(self, balance):
self.balance = balance # routed through setter
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
unsafe = UnsafeAccount(value)
unsafe_result = unsafe.balance
try:
safe = SafeAccount(value)
safe_result = safe.balance
except ValueError as error:
safe_result = str(error)
return {"unsafe": unsafe_result, "safe": safe_result}
8 Inventory Restock Report Medium
Write a function restock_report(starting_quantities, restock_amounts) that builds an InventoryItem class internally with a validated quantity @property (setter raises ValueError("quantity cannot be negative") if value < 0), a restock(self, amount) method that assigns self.quantity = self.quantity + amount (through the setter), and a @staticmethod reorder_threshold() returning 10. For each paired (start, amount) from zip(starting_quantities, restock_amounts), create an item with the starting quantity, call restock(amount), and record {"quantity": item.quantity, "needs_reorder": item.quantity < InventoryItem.reorder_threshold()}. Return the list of these records, in order.
restock_report([5], [20]) → [{"quantity": 25, "needs_reorder": false}]restock_report([], []) → []
Show Solution
def restock_report(starting_quantities, restock_amounts):
class InventoryItem:
def __init__(self, quantity):
self.quantity = quantity
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
if value < 0:
raise ValueError("quantity cannot be negative")
self._quantity = value
def restock(self, amount):
self.quantity = self.quantity + amount
@staticmethod
def reorder_threshold():
return 10
report = []
for start, amount in zip(starting_quantities, restock_amounts):
item = InventoryItem(start)
item.restock(amount)
report.append(
{
"quantity": item.quantity,
"needs_reorder": item.quantity < InventoryItem.reorder_threshold(),
}
)
return report