🐍 Python for Everyone

← Back to practice bank

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

Coding Challenges: Inheritance & Polymorphism

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-16 have covered so far — including class Child(Parent):, super().__init__(...), method overriding, polymorphism, and isinstance()/type() checks. No 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 a small class hierarchy inside your function to model the problem (an Animal with Dog/Cat subclasses, a Shape with Rectangle/Circle subclasses, 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 classes you used internally to compute it.

1 Animal Sounds Roll Call Easy

Write a function animal_sounds(names_and_kinds) that builds an Animal class internally with __init__(self, name) storing self.name and a method speak(self) returning f"{self.name} makes a sound.", a Dog(Animal) subclass overriding speak(self) to return f"{self.name} says Woof!", and a Cat(Animal) subclass overriding speak(self) to return f"{self.name} says Meow!". For each [name, kind] pair in names_and_kinds, create a Dog if kind == "dog", a Cat if kind == "cat", otherwise a plain Animal. Return a list of each animal's speak() result, in order.

Constraints: names_and_kinds may be empty, in which case return an empty list; kind may be any string, including one that isn't "dog" or "cat".
Examples:
animal_sounds([["Rex", "dog"], ["Whiskers", "cat"]]) → ["Rex says Woof!", "Whiskers says Meow!"]
animal_sounds([]) → []
challenge_1.py
Show Solution
solution_1.py
def animal_sounds(names_and_kinds):
    class Animal:
        def __init__(self, name):
            self.name = name

        def speak(self):
            return f"{self.name} makes a sound."

    class Dog(Animal):
        def speak(self):
            return f"{self.name} says Woof!"

    class Cat(Animal):
        def speak(self):
            return f"{self.name} says Meow!"

    animals = []
    for name, kind in names_and_kinds:
        if kind == "dog":
            animals.append(Dog(name))
        elif kind == "cat":
            animals.append(Cat(name))
        else:
            animals.append(Animal(name))

    return [animal.speak() for animal in animals]

2 Build a Manager From an Employee Easy

Write a function build_manager(name, salary, team_size) that builds an Employee class internally with __init__(self, name, salary) storing both, and a Manager(Employee) subclass with __init__(self, name, salary, team_size) that calls super().__init__(name, salary) to reuse the parent's setup, then stores self.team_size = team_size. Create manager = Manager(name, salary, team_size) and return {"name": manager.name, "salary": manager.salary, "team_size": manager.team_size}.

Constraints: salary and team_size are non-negative numbers, including 0.
Examples:
build_manager("Dana", 95000, 4) → {"name": "Dana", "salary": 95000, "team_size": 4}
build_manager("Priya", 60000, 0) → {"name": "Priya", "salary": 60000, "team_size": 0}
challenge_2.py
Show Solution
solution_2.py
def build_manager(name, salary, team_size):
    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary

    class Manager(Employee):
        def __init__(self, name, salary, team_size):
            super().__init__(name, salary)
            self.team_size = team_size

    manager = Manager(name, salary, team_size)
    return {
        "name": manager.name,
        "salary": manager.salary,
        "team_size": manager.team_size,
    }

3 Total Area of Mixed Shapes Easy

Write a function total_shape_area(shapes_spec) that builds a Shape class internally with a method area(self) returning 0, a Rectangle(Shape) subclass with __init__(self, width, height) and an overriding area(self) returning self.width * self.height, and a Circle(Shape) subclass with __init__(self, radius) and an overriding area(self) returning round(3.14159 * self.radius ** 2, 2). Each entry in shapes_spec is either ["rectangle", width, height] or ["circle", radius] — build the matching shape for every entry, then return round(the sum of every shape's area(), 2), calling area() the same way on every shape regardless of its type.

Constraints: shapes_spec may be empty, in which case return 0.
Examples:
total_shape_area([["rectangle", 4, 5], ["circle", 3]]) → 48.27
total_shape_area([]) → 0
challenge_3.py
Show Solution
solution_3.py
def total_shape_area(shapes_spec):
    class Shape:
        def area(self):
            return 0

    class Rectangle(Shape):
        def __init__(self, width, height):
            self.width = width
            self.height = height

        def area(self):
            return self.width * self.height

    class Circle(Shape):
        def __init__(self, radius):
            self.radius = radius

        def area(self):
            return round(3.14159 * self.radius ** 2, 2)

    shapes = []
    for spec in shapes_spec:
        if spec[0] == "rectangle":
            shapes.append(Rectangle(spec[1], spec[2]))
        elif spec[0] == "circle":
            shapes.append(Circle(spec[1]))

    total = 0
    for shape in shapes:
        total += shape.area()
    return round(total, 2)

4 Extend, Don't Replace Medium

Write a function describe_employee(name, team_size) that builds an Employee class internally with __init__(self, name) storing self.name, and a method describe(self) returning f"{self.name} is an employee.". Build a Manager(Employee) subclass with __init__(self, name, team_size) that calls super().__init__(name) and stores self.team_size, and an overriding describe(self) that calls base = super().describe() to get the parent's version, then returns base + f" They manage a team of {self.team_size}." — extending the parent's behavior rather than replacing it. Create manager = Manager(name, team_size) and return manager.describe().

Constraints: team_size is a non-negative integer, including 0.
Examples:
describe_employee("Priya", 6) → "Priya is an employee. They manage a team of 6."
describe_employee("Dana", 0) → "Dana is an employee. They manage a team of 0."
challenge_4.py
Show Solution
solution_4.py
def describe_employee(name, team_size):
    class Employee:
        def __init__(self, name):
            self.name = name

        def describe(self):
            return f"{self.name} is an employee."

    class Manager(Employee):
        def __init__(self, name, team_size):
            super().__init__(name)
            self.team_size = team_size

        def describe(self):
            base = super().describe()
            return base + f" They manage a team of {self.team_size}."

    manager = Manager(name, team_size)
    return manager.describe()

5 Notification Broadcast Medium

Write a function broadcast(messages_and_channels) that builds a Notification class internally with __init__(self, message) storing self.message, and a method send(self) returning f"Generic: {self.message}". Build an EmailNotification(Notification) subclass overriding send(self) to return f"Email: {self.message}", and an SMSNotification(Notification) subclass overriding send(self) to return f"SMS: {self.message}". For each [message, channel] pair in messages_and_channels, create an EmailNotification if channel == "email", an SMSNotification if channel == "sms", otherwise a plain Notification. Return a list of each notification's send() result, calling send() the identical way on every one.

Constraints: messages_and_channels may be empty, in which case return an empty list; channel may be any string, including one that isn't "email" or "sms".
Examples:
broadcast([["Welcome!", "email"], ["Code: 1234", "sms"]]) → ["Email: Welcome!", "SMS: Code: 1234"]
broadcast([]) → []
challenge_5.py
Show Solution
solution_5.py
def broadcast(messages_and_channels):
    class Notification:
        def __init__(self, message):
            self.message = message

        def send(self):
            return f"Generic: {self.message}"

    class EmailNotification(Notification):
        def send(self):
            return f"Email: {self.message}"

    class SMSNotification(Notification):
        def send(self):
            return f"SMS: {self.message}"

    results = []
    for message, channel in messages_and_channels:
        if channel == "email":
            notification = EmailNotification(message)
        elif channel == "sms":
            notification = SMSNotification(message)
        else:
            notification = Notification(message)
        results.append(notification.send())
    return results

6 isinstance() vs. type() Report Medium

Write a function membership_report(kind) that builds a Vehicle class internally with no body other than pass, and a Car(Vehicle) subclass also with no body other than pass. Create obj = Vehicle() if kind == "vehicle", otherwise obj = Car(). Return {"isinstance_vehicle": isinstance(obj, Vehicle), "isinstance_car": isinstance(obj, Car), "type_is_vehicle": type(obj) == Vehicle, "type_is_car": type(obj) == Car} — showing exactly how isinstance() follows the inheritance chain while type() only matches the exact class.

Constraints: kind is always either "vehicle" or "car".
Examples:
membership_report("vehicle") → {"isinstance_vehicle": true, "isinstance_car": false, "type_is_vehicle": true, "type_is_car": false}
membership_report("car") → {"isinstance_vehicle": true, "isinstance_car": true, "type_is_vehicle": false, "type_is_car": true}
challenge_6.py
Show Solution
solution_6.py
def membership_report(kind):
    class Vehicle:
        pass

    class Car(Vehicle):
        pass

    if kind == "vehicle":
        obj = Vehicle()
    else:
        obj = Car()

    return {
        "isinstance_vehicle": isinstance(obj, Vehicle),
        "isinstance_car": isinstance(obj, Car),
        "type_is_vehicle": type(obj) == Vehicle,
        "type_is_car": type(obj) == Car,
    }

7 Filter Managers From Staff Medium

Write a function manager_names(staff_spec) that builds an Employee class internally with __init__(self, name) storing self.name, and a Manager(Employee) subclass with no body other than pass. For each [name, kind] pair in staff_spec, create a Manager if kind == "manager", otherwise a plain Employee. Return a list of the .name of every staff member for which isinstance(person, Manager) is True, preserving the original order.

Constraints: staff_spec may be empty, or contain no managers at all, in which case return an empty list.
Examples:
manager_names([["Sam", "employee"], ["Dana", "manager"]]) → ["Dana"]
manager_names([]) → []
challenge_7.py
Show Solution
solution_7.py
def manager_names(staff_spec):
    class Employee:
        def __init__(self, name):
            self.name = name

    class Manager(Employee):
        pass

    staff = []
    for name, kind in staff_spec:
        if kind == "manager":
            staff.append(Manager(name))
        else:
            staff.append(Employee(name))

    return [person.name for person in staff if isinstance(person, Manager)]

8 Bank Account Hierarchy With a Bonus Subclass Medium

Write a function account_after_operations(owner, starting_balance, is_premium, operations) that builds a BankAccount class internally with __init__(self, owner, balance) storing both, and deposit(self, amount)/withdraw(self, amount) methods that add to or subtract from self.balance. Build a PremiumAccount(BankAccount) subclass with __init__(self, owner, balance) that calls super().__init__(owner, balance + 50) — modeling a signup bonus — with no other overrides. Create a PremiumAccount if is_premium is True, otherwise a plain BankAccount, using starting_balance. Apply every [op, amount] pair in operations in order (calling deposit or withdraw as appropriate). Return {"owner": account.owner, "balance": round(account.balance, 2), "is_premium": isinstance(account, PremiumAccount)}.

Constraints: operations may be empty; every operation always succeeds (no validation is required here).
Examples:
account_after_operations("Dana", 100, false, [["deposit", 50], ["withdraw", 30]]) → {"owner": "Dana", "balance": 120, "is_premium": false}
account_after_operations("Sam", 100, true, []) → {"owner": "Sam", "balance": 150, "is_premium": true}
challenge_8.py
Show Solution
solution_8.py
def account_after_operations(owner, starting_balance, is_premium, operations):
    class BankAccount:
        def __init__(self, owner, balance):
            self.owner = owner
            self.balance = balance

        def deposit(self, amount):
            self.balance += amount

        def withdraw(self, amount):
            self.balance -= amount

    class PremiumAccount(BankAccount):
        def __init__(self, owner, balance):
            super().__init__(owner, balance + 50)

    if is_premium:
        account = PremiumAccount(owner, starting_balance)
    else:
        account = BankAccount(owner, starting_balance)

    for op, amount in operations:
        if op == "deposit":
            account.deposit(amount)
        elif op == "withdraw":
            account.withdraw(amount)

    return {
        "owner": account.owner,
        "balance": round(account.balance, 2),
        "is_premium": isinstance(account, PremiumAccount),
    }
← Practice Bank Interview Questions →