Elif ladder execution in Python - Time & Space Complexity
Let's explore how the time taken by an elif ladder changes as we add more conditions.
We want to know how the program's steps grow when checking multiple conditions one after another.
Analyze the time complexity of the following code snippet.
def check_number(x):
if x == 1:
return "One"
elif x == 2:
return "Two"
elif x == 3:
return "Three"
elif x == 4:
return "Four"
else:
return "Other"
This code checks a number against several conditions one by one until it finds a match.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each condition in the elif ladder one after another.
- How many times: Up to the number of conditions until a match is found or all are checked.
As the number of conditions grows, the program may check more conditions before stopping.
| Number of Conditions (n) | Approx. Checks in Worst Case |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The checks grow directly with the number of conditions, one by one.
Time Complexity: O(n)
This means the time to find a match grows in a straight line as you add more conditions.
[X] Wrong: "The elif ladder checks all conditions every time no matter what."
[OK] Correct: Actually, the program stops checking as soon as it finds a matching condition, so it may not always check all conditions.
Understanding how elif ladders work helps you explain how your code runs step-by-step, a skill useful in many coding discussions.
"What if we replaced the elif ladder with a dictionary lookup? How would the time complexity change?"