0
0
Pythonprogramming~5 mins

Assert statement usage in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assert statement usage
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each number in the list is checked one by one, so the work grows as the list grows.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of checks grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items checked.

Common Mistake

[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.

Interview Connect

Understanding how assert statements affect time helps you write clear and efficient checks in your code, a skill useful in many programming tasks.

Self-Check

"What if we replaced the assert with a simple if-statement that raises an error? How would the time complexity change?"