Methods with parameters in Python - Time & Space Complexity
When we use methods with parameters, we want to know how the time it takes to run changes as the input changes.
We ask: How does the method's work grow when the input values get bigger?
Analyze the time complexity of the following code snippet.
class Calculator:
def multiply(self, numbers):
result = 1
for num in numbers:
result *= num
return result
calc = Calculator()
print(calc.multiply([2, 3, 4, 5]))
This method multiplies all numbers in a list and returns the product.
- Primary operation: Looping through each number in the input list.
- How many times: Once for every number in the list.
As the list gets longer, the method does more multiplications, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The work grows directly with the size of the input list.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[X] Wrong: "The method takes the same time no matter how many numbers are in the list."
[OK] Correct: Because the method must multiply each number, more numbers mean more work and more time.
Understanding how methods with parameters scale helps you explain your code clearly and shows you know how input size affects performance.
"What if the method also called another method inside the loop? How would the time complexity change?"