Assert statement usage in Python - Time & Space Complexity
Let's see how using assert statements affects the time a program takes to run.
We want to know how the program's speed changes as the input grows when asserts are used.
Analyze the time complexity of the following code snippet.
def check_positive(numbers):
for num in numbers:
assert num > 0, f"Number {num} is not positive"
return True
This code checks if all numbers in a list are positive using assert statements inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list and checking with assert.
- How many times: Once for each number in the input list.
Each number in the list is checked one by one, so the work grows as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Assert statements make the program run instantly or take no time."
[OK] Correct: Assert statements still run each time they are reached, so they add to the total work, especially inside loops.
Understanding how assert statements affect time helps you write clear and efficient checks in your code, a skill useful in many programming tasks.
"What if we replaced the assert with a simple if-statement that raises an error? How would the time complexity change?"