Home automation with relay modules in Raspberry Pi - Time & Space Complexity
When controlling home devices with relay modules on a Raspberry Pi, it is important to understand how the time to run the control program changes as you add more devices.
We want to know how the program's work grows when we control many relays.
Analyze the time complexity of the following code snippet.
relay_pins = [17, 18, 27, 22]
for pin in relay_pins:
setup_pin(pin, "OUTPUT")
for pin in relay_pins:
turn_on_relay(pin)
wait(1) # wait 1 second
turn_off_relay(pin)
This code sets up several relay pins and then turns each relay on and off one by one with a delay.
- Primary operation: Looping through the list of relay pins twice.
- How many times: Once for setup, once for turning relays on and off, each time for every relay.
As the number of relays increases, the program runs more setup and control steps, one for each relay.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (2 loops x 10 relays) |
| 100 | About 200 steps |
| 1000 | About 2000 steps |
Pattern observation: The total work grows directly with the number of relays; doubling relays doubles the work.
Time Complexity: O(n)
This means the time to run the program grows in a straight line with the number of relays you control.
[X] Wrong: "Adding more relays won't affect the time much because each relay works independently."
[OK] Correct: Even if relays work independently, the program still loops through each one, so more relays mean more steps to run.
Understanding how your program's work grows with more devices shows you can write efficient code for real home automation projects.
"What if we turned on all relays at the same time instead of one by one? How would the time complexity change?"