Unit conversion utilities in SciPy - Time & Space Complexity
We want to understand how the time needed to convert units changes as we convert more values.
How does the work grow when we convert many numbers instead of just one?
Analyze the time complexity of the following code snippet.
def convert_temperatures(celsius_values):
fahrenheit_values = []
for c in celsius_values:
f = c * 9 / 5 + 32
fahrenheit_values.append(f)
return fahrenheit_values
# Example usage:
celsius_list = [0, 20, 100]
convert_temperatures(celsius_list)
This code converts a list of temperatures from Celsius to Fahrenheit one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each temperature value to convert it.
- How many times: Once for each temperature in the input list.
As the number of temperatures to convert grows, the total work grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 conversions |
| 100 | About 100 conversions |
| 1000 | About 1000 conversions |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to convert temperatures grows directly with how many values you have.
[X] Wrong: "Converting many temperatures takes the same time as converting one."
[OK] Correct: Each temperature needs its own calculation, so more values mean more work.
Understanding how time grows with input size helps you explain your code's efficiency clearly and confidently.
"What if we used a vectorized operation from scipy to convert all temperatures at once? How would the time complexity change?"