Skip to the content.

3.17 Homework Hacks

My answers for the Homework hacks

CSP Big Idea 3.17

Write a function that takes the following inputs:

An array: arr = [5, 10, 15, 20, 25] A string representing the time complexity: “constant”, “linear”, “quadratic”, etc. The function should perform operations on the array based on the given time complexity. For example:

If the string is “constant”, return the first item of the array. If the string is “linear”, print all the items in the array. If the string is “quadratic”, print all pairs of items in the array.

def run_based_on_complexity(arr, complexity):
    if complexity == "constant":
        return arr[0]

    elif complexity == "linear":
        for item in arr:
            print(item)

    elif complexity == "quadratic":
        for i in range(len(arr)):
            for j in range(len(arr)):
                print(f"({arr[i]}, {arr[j]})")

# Example usage:
arr = [5, 10, 15, 20, 25]

print(run_based_on_complexity(arr, "constant"))  # Output: 5
run_based_on_complexity(arr, "linear")          # Prints each item
run_based_on_complexity(arr, "quadratic")       # Prints all pairs

5
5
10
15
20
25
(5, 5)
(5, 10)
(5, 15)
(5, 20)
(5, 25)
(10, 5)
(10, 10)
(10, 15)
(10, 20)
(10, 25)
(15, 5)
(15, 10)
(15, 15)
(15, 20)
(15, 25)
(20, 5)
(20, 10)
(20, 15)
(20, 20)
(20, 25)
(25, 5)
(25, 10)
(25, 15)
(25, 20)
(25, 25)