Coding Challenges: Functions Deep Dive
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 like n = 0 and empty inputs).
Stuck? Every challenge has a Show Solution reveal at
the bottom. Only uses what Chapters 1-10 have covered so far —
def, default arguments, *args/**kwargs,
global/nonlocal, recursion, closures, and
hand-written decorators. No try/except, file
I/O, classes, or imports.
1 Price With Tax Easy
Write a function price_with_tax(price, tax_rate=0.08) that returns price plus tax_rate of price, rounded to 2 decimal places, using a default argument for tax_rate.
price may be 0; tax_rate may be overridden by the caller; round the final result to 2 decimal places with round(..., 2).
price_with_tax(100) → 108.0price_with_tax(100, 0.1) → 110.0price_with_tax(0) → 0.0
Show Solution
def price_with_tax(price, tax_rate=0.08):
return round(price + price * tax_rate, 2)
2 Sum Any Number of Values Easy
Write a function total_of(*args) that returns the sum of however many positional arguments are passed in, using *args.
0); arguments may be negative.
total_of(1, 2, 3) → 6total_of() → 0total_of(-1, 1) → 0
Show Solution
def total_of(*args):
return sum(args)
3 Format a Record From Keyword Arguments Easy
Write a function format_record(fields) that takes a dictionary fields and returns a single string joining every entry as "key=value" pairs separated by ", ", in insertion order. Do the actual joining inside a small nested helper that takes **kwargs, and call that helper by unpacking the dict into it with **fields — that's the **kwargs pattern this challenge is really testing, just wired up so the outside caller can hand you a single dict.
fields may be an empty dict (return ""); values may be strings or numbers.
format_record({"name": "Asha", "age": 21}) → "name=Asha, age=21"format_record({}) → ""format_record({"x": 1}) → "x=1"
Show Solution
def format_record(fields):
def _format(**kwargs):
return ", ".join(f"{k}={v}" for k, v in kwargs.items())
return _format(**fields)
4 Recursive Factorial Easy
Write a recursive function factorial(n) that returns n! (the product of every whole number from 1 to n), with factorial(0) equal to 1 as the base case.
n is always a non-negative integer; must be implemented recursively (no loop-based fallback).
factorial(0) → 1factorial(5) → 120factorial(10) → 3628800
Show Solution
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
5 Recursive Digit Sum Medium
Write a recursive function digit_sum(n) that returns the sum of the digits of n. The base case is when n is already a single digit (less than 10) — return n directly. Otherwise, return the last digit (n % 10) plus the recursive digit sum of the rest of the number (n // 10).
n is always a non-negative integer, including 0; must be implemented recursively.
digit_sum(0) → 0digit_sum(123) → 6digit_sum(9999) → 36
Show Solution
def digit_sum(n):
if n < 10:
return n
return (n % 10) + digit_sum(n // 10)
6 Count Numbers in a Nested List Medium
Write a recursive function count_numbers(data) that takes a list which may contain numbers and/or other nested lists (nested arbitrarily deep), and returns a count of how many individual numbers appear in total, at every level.
data may be empty, or contain empty nested lists (they contribute 0); nesting depth is not fixed.
count_numbers([1, 2, [3, 4], [5, [6, 7, 8]]]) → 8count_numbers([]) → 0count_numbers([1, [2, [3, [4]]]]) → 4
Show Solution
def count_numbers(data):
count = 0
for item in data:
if isinstance(item, list):
count += count_numbers(item)
else:
count += 1
return count
7 Closure-Based Running Totals Medium
Write a function running_totals(amounts) that builds a closure-based accumulator internally: a local total = 0, plus a nested function add(amount) that uses nonlocal total to add amount to total and return the new running total. Then, using that same add closure, process every value in amounts in order and return a list of the running total after each one.
amounts may be empty (return []); values may be negative; the running total must persist across every value in amounts via nonlocal, not be recomputed from scratch each time.
running_totals([10, 5, -3]) → [10, 15, 12]running_totals([]) → []running_totals([1, 1, 1, 1]) → [1, 2, 3, 4]
Show Solution
def running_totals(amounts):
total = 0
def add(amount):
nonlocal total
total += amount
return total
return [add(amount) for amount in amounts]
8 Call-Counting Decorator Medium
Write a function call_n_times(n) that, internally, defines a small function ping() returning "pong", and a decorator with_call_count(fn) that wraps fn so every call to the wrapped version calls the original fn (ignoring its return value) and instead returns how many times the wrapped function has been called so far, starting at 1 on the first call (track the running count with nonlocal inside the decorator). Wrap ping with with_call_count, call the wrapped version n times, and return the result of the final call (0 if n is 0, since the wrapped function is never called).
n may be 0 (return 0); the call count must start at 1 on the first call and increase by 1 each subsequent call.
call_n_times(3) → 3call_n_times(1) → 1call_n_times(0) → 0
Show Solution
def call_n_times(n):
def with_call_count(fn):
calls = 0
def wrapper(*args, **kwargs):
nonlocal calls
calls += 1
fn(*args, **kwargs)
return calls
return wrapper
def ping():
return "pong"
counted_ping = with_call_count(ping)
result = 0
for _ in range(n):
result = counted_ping()
return result