🐍 Python for Everyone

← Back to practice bank

Chapter 25 Coding Challenges 45-60 min, auto-graded

Coding Challenges: Memory Management in Python

8 HackerRank-style challenges, auto-graded right in your browser — no local install needed, standard library only. 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-25 have covered so far.

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. A couple of these challenges grade a relative memory comparison (e.g. "is A smaller than B?" as True/False) rather than an exact byte count, since exact byte counts can vary by Python version/platform — this keeps every challenge portable.

1 Refcount Change on Alias Easy

Write a function refcount_change_on_alias(obj) that takes sys.getrefcount(obj), creates one new alias (a second reference) to obj, takes the refcount again, and returns the difference (an int) between the second reading and the first.

Constraints: obj can be any object (a list, string, or number).
Examples:
refcount_change_on_alias([1, 2, 3]) → 1
challenge_1.py
Show Solution
solution_1.py
import sys

def refcount_change_on_alias(obj):
    before = sys.getrefcount(obj)
    alias = obj
    after = sys.getrefcount(obj)
    return after - before

2 Would It Leak Without gc? Medium

Write a function would_leak_without_gc(has_cycle, gc_enabled) that returns True only when there's a real leak risk: a reference cycle exists (has_cycle is True) and the cyclic collector is off (gc_enabled is False). Otherwise return False.

Constraints: both arguments are booleans.
Examples:
would_leak_without_gc(True, False) → True
would_leak_without_gc(True, True) → False
challenge_2.py
Show Solution
solution_2.py
def would_leak_without_gc(has_cycle, gc_enabled):
    return has_cycle and not gc_enabled

3 Safe Append (Fix the Default) Easy

Write a function safe_append(item, items=None) that correctly avoids the mutable default argument gotcha: if items is not given, start from a fresh empty list every call, append item, and return the list.

Constraints: item can be any value; items, if given, is a list.
Examples:
safe_append("a") → ["a"]
safe_append("b") → ["b"] (not ["a", "b"])
challenge_3.py
Show Solution
solution_3.py
def safe_append(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

4 Simulate the Shared-Default Bug Medium

Write a function append_n_times_broken(n) that simulates the classic mutable default argument bug directly: define a local helper def _broken(item, cart=[]) inside append_n_times_broken, call it n times in a row with items 0, 1, 2, ..., n-1 (not resetting cart between calls), and return the final call's result as a plain list.

Constraints: n is a non-negative int.
Examples:
append_n_times_broken(3) → [0, 1, 2] (every call shared the same growing list)
append_n_times_broken(1) → [0]
challenge_4.py
Show Solution
solution_4.py
def append_n_times_broken(n):
    def _broken(item, cart=[]):
        cart.append(item)
        return cart

    result = []
    for i in range(n):
        result = _broken(i)
    return result

5 Slotted vs. Regular Instance Size Medium

Write a function is_slotted_smaller(x, y) that builds two classes internally — one regular, one using __slots__ = ("x", "y") — each with matching __init__(self, x, y), creates one instance of each with the given values, and returns True if the slotted instance's sys.getsizeof() plus nothing else is strictly smaller than the regular instance's sys.getsizeof() plus its __dict__'s sys.getsizeof() combined.

Constraints: x and y are plain values (numbers or strings).
Examples:
is_slotted_smaller(1, 2) → True
challenge_5.py
Show Solution
solution_5.py
import sys

def is_slotted_smaller(x, y):
    class Regular:
        def __init__(self, x, y):
            self.x = x
            self.y = y

    class Slotted:
        __slots__ = ("x", "y")

        def __init__(self, x, y):
            self.x = x
            self.y = y

    r = Regular(x, y)
    s = Slotted(x, y)
    regular_total = sys.getsizeof(r) + sys.getsizeof(r.__dict__)
    slotted_total = sys.getsizeof(s)
    return slotted_total < regular_total

6 Object Byte Size Easy

Write a function object_byte_size(obj) that returns sys.getsizeof(obj) as a plain int.

Constraints: obj can be any object.
Examples:
object_byte_size([1, 2, 3]) → an int greater than 0.
challenge_6.py
Show Solution
solution_6.py
import sys

def object_byte_size(obj):
    return sys.getsizeof(obj)

7 Is the Generator Lighter? Medium

Write a function is_generator_lighter(n) that uses tracemalloc to compare, at the moment of creation, the peak memory of a list comprehension [i for i in range(n)] against the equivalent generator expression (i for i in range(n)). Return True if the generator's peak is strictly less than the list's peak, else False. Measure the generator's memory before consuming it.

Constraints: n is a positive int.
Examples:
is_generator_lighter(1000) → True
challenge_7.py
Show Solution
solution_7.py
import tracemalloc

def is_generator_lighter(n):
    tracemalloc.start()
    lst = [i for i in range(n)]
    _, list_peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    tracemalloc.start()
    gen = (i for i in range(n))
    _, gen_peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    return gen_peak < list_peak

8 List vs. Set for the Same Data Medium

Write a function smaller_container_name(n) that measures peak memory (using tracemalloc) for a list(range(n)) versus a set(range(n)), and returns the string "list" or "set", whichever measured a strictly smaller peak.

Constraints: n is a positive int.
Examples:
smaller_container_name(1000) → "list"
challenge_8.py
Show Solution
solution_8.py
import tracemalloc

def smaller_container_name(n):
    tracemalloc.start()
    lst = list(range(n))
    _, list_peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    tracemalloc.start()
    st = set(range(n))
    _, set_peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    return "list" if list_peak < set_peak else "set"
← Practice Bank Interview Questions →