Logical operators in Python - Time & Space Complexity
Logical operators combine true or false values to make decisions in code.
We want to see how the time to run code changes when using these operators.
Analyze the time complexity of the following code snippet.
def check_values(a, b, c):
if a and b:
return True
elif b or c:
return True
else:
return False
This code checks combinations of three values using logical AND and OR.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple logical checks (and, or) on fixed inputs.
- How many times: Each check happens once per function call.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 (a,b,c) | Up to 3 checks |
| 10 (if extended) | Still about 3 checks per call |
| 100 (if extended) | Still about 3 checks per call |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the time to run does not grow with input size; it stays constant.
[X] Wrong: "Logical operators take longer as inputs get bigger."
[OK] Correct: Logical operators check fixed values and stop early, so time does not increase with input size.
Understanding that logical operations run quickly and do not slow down with input size helps you write efficient decision-making code.
"What if we used logical operators inside a loop over a list of size n? How would the time complexity change?"