Infinite loop prevention in Python - Time & Space Complexity
When we write loops, it is important to know how long they run. This helps us avoid loops that never stop, called infinite loops.
We want to understand how the number of steps grows as the loop runs.
Analyze the time complexity of the following code snippet.
count = 0
while count < 5:
print(count)
count += 1
This code prints numbers from 0 to 4 by increasing count each time until it reaches 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly.
- How many times: It runs 5 times, once for each number from 0 to 4.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 loops |
| 10 | 10 loops |
| 100 | 100 loops |
Pattern observation: The number of steps grows directly with the input size. If input doubles, steps double too.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the input size.
[X] Wrong: "The loop will always stop quickly no matter what."
[OK] Correct: If the loop condition never changes, the loop can run forever, causing an infinite loop.
Understanding how loops grow and stop is a key skill. It shows you can write safe code that finishes and does not get stuck.
"What if we forgot to increase count inside the loop? How would the time complexity change?"