Coding Challenges: OOP Basics
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-14 have covered so far — including class definitions,
__init__, instance attributes, class attributes, instance
methods, and __str__/__repr__. No
@staticmethod, @classmethod,
@property, inheritance, or any import beyond
math/datetime/random/csv.
Rectangle with area()
and perimeter(), a BankAccount with
deposit()/withdraw(), and so on), but the
function itself always returns a plain number, string, 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 Rectangle Dimensions Easy
Write a function rectangle_dimensions(width, height) that builds a Rectangle class internally with __init__(self, width, height), an area(self) method returning self.width * self.height, and a perimeter(self) method returning 2 * (self.width + self.height). Create one instance and return {"area": rect.area(), "perimeter": rect.perimeter()}.
width and height are non-negative numbers; either may be 0.
rectangle_dimensions(4, 5) → {"area": 20, "perimeter": 18}rectangle_dimensions(0, 5) → {"area": 0, "perimeter": 10}
Show Solution
def rectangle_dimensions(width, height):
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
rect = Rectangle(width, height)
return {"area": rect.area(), "perimeter": rect.perimeter()}
2 The Shared List Gotcha Easy
Write a function demonstrate_shared_class_list(item_to_add) that defines a class Cart with a class attribute items = [] (not an instance attribute) and a method add_item(self, item) that appends to self.items. Create cart_one = Cart() and cart_two = Cart(), call cart_one.add_item(item_to_add), and return cart_two.items — showing what actually happens to the second cart's items because of the shared class-level list.
item_to_add is always a non-empty string.
demonstrate_shared_class_list("Book") → ["Book"]demonstrate_shared_class_list("Pen") → ["Pen"]
Show Solution
def demonstrate_shared_class_list(item_to_add):
class Cart:
items = [] # class attribute -- shared by every instance (the gotcha)
def add_item(self, item):
self.items.append(item)
cart_one = Cart()
cart_two = Cart()
cart_one.add_item(item_to_add)
return cart_two.items
3 Formatted Money String Easy
Write a function format_money(amount, currency) that builds a Money class internally with __init__(self, amount, currency) and a __str__(self) method returning f"{self.amount:.2f} {self.currency}". Create one instance and return str(money).
amount may be an int or a float, including 0.
format_money(19.9, "USD") → "19.90 USD"format_money(0, "EUR") → "0.00 EUR"
Show Solution
def format_money(amount, currency):
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __str__(self):
return f"{self.amount:.2f} {self.currency}"
return str(Money(amount, currency))
4 Same Coordinates? Easy
Write a function same_point(x1, y1, x2, y2) that builds a Point class internally with __init__(self, x, y), creates point_a = Point(x1, y1) and point_b = Point(x2, y2), and returns True if both instances' .x and .y attributes match, False otherwise.
same_point(1, 2, 1, 2) → Truesame_point(1, 2, 2, 1) → False
Show Solution
def same_point(x1, y1, x2, y2):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
point_a = Point(x1, y1)
point_b = Point(x2, y2)
return point_a.x == point_b.x and point_a.y == point_b.y
5 Bank Account Simulation Medium
Write a function simulate_account(starting_balance, operations) that builds a BankAccount class internally with __init__(self, balance), a deposit(self, amount) method, and a withdraw(self, amount) method. Create one instance with starting_balance, then apply every [op, amount] pair in operations in order (op is either "deposit" or "withdraw"), and return the account's final balance.
operations may be empty, in which case the starting balance is returned unchanged; a withdrawal may bring the balance below zero (no overdraft check needed).
simulate_account(100, [["deposit", 50], ["withdraw", 30]]) → 120simulate_account(0, []) → 0
Show Solution
def simulate_account(starting_balance, operations):
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
account = BankAccount(starting_balance)
for op, amount in operations:
if op == "deposit":
account.deposit(amount)
elif op == "withdraw":
account.withdraw(amount)
return account.balance
6 Auto-Incrementing Task Ids Medium
Write a function assign_task_ids(descriptions) that builds a Task class internally with a class attribute next_id = 1 and __init__(self, description) that sets self.id = Task.next_id, stores self.description = description, and then increments Task.next_id by 1. Create one Task per string in descriptions, in order, and return a list of each task's .id.
descriptions may be an empty list, in which case return an empty list; ids always start at 1 for each call.
assign_task_ids(["Write report", "Review PR"]) → [1, 2]assign_task_ids([]) → []
Show Solution
def assign_task_ids(descriptions):
class Task:
next_id = 1
def __init__(self, description):
self.id = Task.next_id
self.description = description
Task.next_id += 1
tasks = [Task(description) for description in descriptions]
return [task.id for task in tasks]
7 Total Inventory Value Medium
Write a function total_inventory_value(items) that builds an InventoryItem class internally with __init__(self, name, quantity, unit_price) and a total_value(self) method returning self.quantity * self.unit_price. items is a list of [name, quantity, unit_price] lists; create one InventoryItem per entry and return the sum of every item's total_value(), rounded to 2 decimal places.
items may be empty, in which case return 0.0.
total_inventory_value([["Widget", 10, 2.5], ["Gadget", 4, 9.99]]) → 64.96total_inventory_value([]) → 0.0
Show Solution
def total_inventory_value(items):
class InventoryItem:
def __init__(self, name, quantity, unit_price):
self.name = name
self.quantity = quantity
self.unit_price = unit_price
def total_value(self):
return self.quantity * self.unit_price
inventory = [
InventoryItem(name, quantity, unit_price)
for name, quantity, unit_price in items
]
return round(sum(item.total_value() for item in inventory), 2)
8 Task Manager Status Counts Medium
Write a function count_task_statuses(descriptions, done_indexes) that builds a Task class internally with __init__(self, description) storing self.description and self.done = False, plus a mark_done(self) method setting self.done = True. Create one Task per string in descriptions (in order), call mark_done() on every task whose position appears in done_indexes, and return {"done": <count>, "pending": <count>}.
done_indexes may be empty; descriptions may be empty, in which case return {"done": 0, "pending": 0}.
count_task_statuses(["A", "B", "C"], [0, 2]) → {"done": 2, "pending": 1}count_task_statuses(["A", "B"], []) → {"done": 0, "pending": 2}
Show Solution
def count_task_statuses(descriptions, done_indexes):
class Task:
def __init__(self, description):
self.description = description
self.done = False
def mark_done(self):
self.done = True
tasks = [Task(description) for description in descriptions]
for index in done_indexes:
tasks[index].mark_done()
done_count = sum(1 for task in tasks if task.done)
pending_count = sum(1 for task in tasks if not task.done)
return {"done": done_count, "pending": pending_count}