🐍 Python for Everyone

← Back to practice bank

Chapter 14 Coding Challenges 55-70 min, auto-graded

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.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.
Why every challenge returns a plain value, not an object The auto-grader compares your function's return value to a JSON-safe expected value (a number, string, boolean, list, or dict) — it can't compare custom class instances directly. So every challenge here asks you to build and use a class inside your function to model the problem (a 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()}.

Constraints: width and height are non-negative numbers; either may be 0.
Examples:
rectangle_dimensions(4, 5) → {"area": 20, "perimeter": 18}
rectangle_dimensions(0, 5) → {"area": 0, "perimeter": 10}
challenge_1.py
Show Solution
solution_1.py
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.

Constraints: item_to_add is always a non-empty string.
Examples:
demonstrate_shared_class_list("Book") → ["Book"]
demonstrate_shared_class_list("Pen") → ["Pen"]
challenge_2.py
Show Solution
solution_2.py
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).

Constraints: amount may be an int or a float, including 0.
Examples:
format_money(19.9, "USD") → "19.90 USD"
format_money(0, "EUR") → "0.00 EUR"
challenge_3.py
Show Solution
solution_3.py
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.

Constraints: coordinates may be negative, zero, or positive integers.
Examples:
same_point(1, 2, 1, 2) → True
same_point(1, 2, 2, 1) → False
challenge_4.py
Show Solution
solution_4.py
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.

Constraints: 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).
Examples:
simulate_account(100, [["deposit", 50], ["withdraw", 30]]) → 120
simulate_account(0, []) → 0
challenge_5.py
Show Solution
solution_5.py
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.

Constraints: descriptions may be an empty list, in which case return an empty list; ids always start at 1 for each call.
Examples:
assign_task_ids(["Write report", "Review PR"]) → [1, 2]
assign_task_ids([]) → []
challenge_6.py
Show Solution
solution_6.py
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.

Constraints: items may be empty, in which case return 0.0.
Examples:
total_inventory_value([["Widget", 10, 2.5], ["Gadget", 4, 9.99]]) → 64.96
total_inventory_value([]) → 0.0
challenge_7.py
Show Solution
solution_7.py
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>}.

Constraints: done_indexes may be empty; descriptions may be empty, in which case return {"done": 0, "pending": 0}.
Examples:
count_task_statuses(["A", "B", "C"], [0, 2]) → {"done": 2, "pending": 1}
count_task_statuses(["A", "B"], []) → {"done": 0, "pending": 2}
challenge_8.py
Show Solution
solution_8.py
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}
← Practice Bank Interview Questions →