🐍 Python for Everyone

← Back to practice bank

Chapter 20 Coding Challenges 50-65 min, auto-graded

Coding Challenges: Multithreading

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. Every challenge's output is fully deterministic — none of them depend on unpredictable thread timing, even the ones that use threads internally. Only uses what Chapters 1-20 have covered so far. No import beyond json/os/re/math/datetime/random/csv/threading/concurrent.futures.

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.

1 Classify I/O-Bound vs. CPU-Bound Easy

Write a function classify_work_type(task_name) that returns "I/O-bound" if task_name is one of "download", "api_call", "database_query", "file_read", or "upload", and "CPU-bound" otherwise.

Constraints: task_name is always a string.
Examples:
classify_work_type("download") → "I/O-bound"
classify_work_type("compute_primes") → "CPU-bound"
challenge_1.py
Show Solution
solution_1.py
def classify_work_type(task_name):
    io_tasks = {"download", "api_call", "database_query", "file_read", "upload"}
    if task_name in io_tasks:
        return "I/O-bound"
    return "CPU-bound"

2 Estimate a Speedup Easy

Write a function estimate_speedup(sequential_seconds, threaded_seconds) that returns how many times faster the threaded version was, as round(sequential_seconds / threaded_seconds, 2).

Constraints: threaded_seconds is always greater than 0.
Examples:
estimate_speedup(6, 2) → 3.0
estimate_speedup(10, 10) → 1.0
challenge_2.py
Show Solution
solution_2.py
def estimate_speedup(sequential_seconds, threaded_seconds):
    return round(sequential_seconds / threaded_seconds, 2)

3 Square Every Item Concurrently Medium

Write a function square_all_concurrently(items) that starts one thread per number in items (each thread squaring its number and appending the result to a shared list), joins every thread, and returns the results as a sorted list (sorting removes any dependence on which thread happened to finish first).

Constraints: items is a list of integers, and may be empty.
Examples:
square_all_concurrently([1, 2, 3]) → [1, 4, 9]
challenge_3.py
Show Solution
solution_3.py
import threading

def square_all_concurrently(items):
    results = []
    threads = [threading.Thread(target=lambda n=n: results.append(n * n)) for n in items]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return sorted(results)

4 Safely Total Amounts Across Threads Medium

Write a function safe_total(amounts) that starts one thread per number in amounts, each thread safely adding its number to a shared total using a threading.Lock(), joins every thread, and returns the final total. Must return the mathematically correct sum every time, regardless of thread timing.

Constraints: amounts is a list of integers, and may be empty.
Examples:
safe_total([1, 2, 3, 4]) → 10
safe_total([]) → 0
challenge_4.py
Show Solution
solution_4.py
import threading

def safe_total(amounts):
    total = 0
    lock = threading.Lock()

    def add(amount):
        nonlocal total
        with lock:
            total += amount

    threads = [threading.Thread(target=add, args=(a,)) for a in amounts]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return total

5 Does This Operation Release the GIL? Easy

Write a function gil_releases_for(operation) that returns True if operation is one of "sleep", "network_call", "file_read", "database_query", or "download" (I/O operations that release the GIL while waiting), and False otherwise.

Constraints: operation is always a string.
Examples:
gil_releases_for("sleep") → true
gil_releases_for("tight_loop") → false
challenge_5.py
Show Solution
solution_5.py
def gil_releases_for(operation):
    io_ops = {"sleep", "network_call", "file_read", "database_query", "download"}
    return operation in io_ops

6 Would a Lock Be Needed? Medium

Write a function would_lock_be_needed(threads_read, threads_write) that returns True if a lock would be needed to safely share state given threads_read threads reading and threads_write threads writing the same shared value, and False otherwise. A lock is needed whenever at least one thread writes and more than one thread (reading or writing, combined) touches the value.

Constraints: threads_read and threads_write are non-negative integers.
Examples:
would_lock_be_needed(2, 2) → true (multiple readers and writers)
would_lock_be_needed(3, 0) → false (read-only, nothing being mutated)
would_lock_be_needed(0, 1) → false (only one thread touches it at all)
challenge_6.py
Show Solution
solution_6.py
def would_lock_be_needed(threads_read, threads_write):
    total = threads_read + threads_write
    return threads_write >= 1 and total > 1

7 Double Every Item Using a Thread Pool Medium

Write a function double_with_pool(items, max_workers) that uses ThreadPoolExecutor(max_workers=max_workers) as a context manager, maps a doubling function across items with .map(), and returns the result as a plain list (already in input order, since that's what .map() guarantees).

Constraints: items is a list of integers; max_workers is always a positive integer.
Examples:
double_with_pool([1, 2, 3, 4], 2) → [2, 4, 6, 8]
challenge_7.py
Show Solution
solution_7.py
from concurrent.futures import ThreadPoolExecutor

def double_with_pool(items, max_workers):
    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        return list(pool.map(lambda n: n * 2, items))

8 Combine Per-Thread Results Easy

Write a function combine_thread_results(per_thread_totals) that returns the sum of every value in the list per_thread_totals — standing in for the final "combine after every thread finishes" step of the shared-nothing pattern. Return 0 if the list is empty.

Constraints: per_thread_totals is a list of integers, and may be empty.
Examples:
combine_thread_results([500500, 500500, 500500, 500500]) → 2002000
combine_thread_results([]) → 0
challenge_8.py
Show Solution
solution_8.py
def combine_thread_results(per_thread_totals):
    return sum(per_thread_totals)
← Practice Bank Interview Questions →