Traffic light simulation in Raspberry Pi - Time & Space Complexity
When simulating a traffic light, we want to know how the program's running time changes as we add more cycles or lights.
We ask: How does the time to run the simulation grow when we increase the number of light changes?
Analyze the time complexity of the following code snippet.
for cycle in range(num_cycles):
turn_on_red()
wait(red_duration)
turn_on_green()
wait(green_duration)
turn_on_yellow()
wait(yellow_duration)
# End of simulation
This code runs a traffic light sequence for a set number of cycles, turning lights on and waiting for their durations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that repeats the light changes for each cycle.
- How many times: Exactly
num_cyclestimes, once per cycle.
Each cycle runs the same fixed steps of turning lights on and waiting.
| Input Size (num_cycles) | Approx. Operations |
|---|---|
| 10 | About 10 cycles of light changes |
| 100 | About 100 cycles of light changes |
| 1000 | About 1000 cycles of light changes |
Pattern observation: The total work grows directly with the number of cycles; doubling cycles doubles the work.
Time Complexity: O(n)
This means the time to run the simulation grows in a straight line as you add more cycles.
[X] Wrong: "The time to run the simulation stays the same no matter how many cycles we have."
[OK] Correct: Each cycle repeats the same steps, so more cycles mean more total time.
Understanding how loops affect running time helps you explain how programs scale, a key skill in many coding tasks.
"What if we added a nested loop inside each cycle to blink the yellow light multiple times? How would the time complexity change?"