Skip to content
Chapter Practice Arena

Algorithms and Capstone Practice Problems

Targeted practice challenges specifically curated for this chapter. Inspect hints, verify outputs, and check Pythonic solutions.

All Chapters
Difficulty:
Chapter:
Showing 6 challenges · 33 total · Page 1 of 6
A function checks each task in a list until it finds a matching ID. Explain its worst-case time complexity and auxiliary space complexity. Then explain why get_next_id() in this project takes linear time.
Starter Code
# Explain your answers in comments or plain text.
# Worst-case search time:
# Auxiliary space:
# Time for get_next_id():
Expected Output:Worst-case search time: O(n) Auxiliary space: O(1) get_next_id(): O(n)
Write a function linear_search(items, target) that returns the index of the first matching element. Return -1 if the target is absent. Test it with [8, 2, 5, 9] for targets 5 and 7.
Starter Code
def linear_search(items, target):
    # Visit each valid index.
    # Return the index when the target matches.
    # Return -1 if no match is found.
    pass

numbers = [8, 2, 5, 9]
print(linear_search(numbers, 5))
print(linear_search(numbers, 7))
Expected Output:2 -1
Write countdown(n) that prints every positive integer from n down to 1 and stops when n <= 0. Calling countdown(3) should print 3, 2, and 1 on separate lines. Calling countdown(0) should print nothing.
Starter Code
def countdown(n):
    # Write the base case and recursive case
    pass

countdown(3)
Expected Output:3 2 1
Write pseudocode and a Python function classify_number(n) that returns "Positive" when n is greater than zero, "Negative" when n is less than zero, and "Zero" otherwise. Test all three cases.
Starter Code
def classify_number(n):
    # Check whether n is positive.
    # Otherwise, check whether n is negative.
    # Handle zero explicitly.
    pass

print(classify_number(5))
print(classify_number(-3))
print(classify_number(0))
Expected Output:Positive Negative Zero
Write two unittest test methods for a function summarize(values) that returns {'count': len(values), 'total': sum(values)}. One test must check [2, 3, 5]; the other must check an empty list.
Starter Code
import unittest

def summarize(values):
    return {"count": len(values), "total": sum(values)}

class TestSummarize(unittest.TestCase):
    # Add two test methods.
    pass
Expected Output:Two passing tests when run with Python's unittest runner.
#6intermediateRecursion and Base Cases
The function below is intended to calculate the sum of integers from 1 through n, but it returns the wrong answer. Fix it so that broken_sum(4) returns 10. Explain why the original function was incorrect.
Starter Code
def broken_sum(n):
    if n == 0:
        return 0
    broken_sum(n - 1)
    return n

print(broken_sum(4))
Expected Output:10
…