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.
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.
obj can be any object (a list, string, or number).
refcount_change_on_alias([1, 2, 3]) → 1
Show Solution
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.
would_leak_without_gc(True, False) → Truewould_leak_without_gc(True, True) → False
Show Solution
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.
item can be any value; items, if given, is a list.
safe_append("a") → ["a"]safe_append("b") → ["b"] (not ["a", "b"])
Show Solution
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.
n is a non-negative int.
append_n_times_broken(3) → [0, 1, 2] (every call shared the same growing list)append_n_times_broken(1) → [0]
Show Solution
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.
x and y are plain values (numbers or strings).
is_slotted_smaller(1, 2) → True
Show Solution
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.
obj can be any object.
object_byte_size([1, 2, 3]) → an int greater than 0.
Show Solution
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.
n is a positive int.
is_generator_lighter(1000) → True
Show Solution
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.
n is a positive int.
smaller_container_name(1000) → "list"
Show Solution
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"