Polymorphism through functions in Python - Time & Space Complexity
Let's explore how the time needed to run a function changes when it can work with different types of inputs.
We want to see how the function's work grows as the input size grows.
Analyze the time complexity of the following code snippet.
def process(items):
result = []
for item in items:
result.append(str(item))
return result
values = [1, 2, 3, 4, 5]
print(process(values))
This function takes a list of items and converts each item to a string, collecting the results.
- Primary operation: Looping through each item in the input list.
- How many times: Once for every item in the list.
As the list gets bigger, the function does more work by converting more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions |
| 100 | 100 conversions |
| 1000 | 1000 conversions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Polymorphism makes the function slower because it handles different types."
[OK] Correct: The function still processes each item once; the type difference does not add extra loops or steps.
Understanding how functions handle different inputs without extra cost shows you know how to write flexible and efficient code.
"What if the function called another function inside the loop that itself loops over the item? How would the time complexity change?"