LED class and methods in Raspberry Pi - Time & Space Complexity
We want to understand how the time it takes to control LEDs grows as we use more LEDs or call methods multiple times.
How does the number of LEDs or method calls affect the total work done?
Analyze the time complexity of the following code snippet.
class LED:
def __init__(self, pin):
self.pin = pin
self.state = False
def turn_on(self):
self.state = True
def turn_off(self):
self.state = False
leds = [LED(pin) for pin in range(5)]
for led in leds:
led.turn_on()
This code creates 5 LED objects and turns each one on by calling the turn_on method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
turn_onmethod on each LED object. - How many times: Once for each LED in the list (5 times in this example).
As the number of LEDs increases, the number of times we call turn_on grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to turn_on |
| 100 | 100 calls to turn_on |
| 1000 | 1000 calls to turn_on |
Pattern observation: The work grows directly with the number of LEDs.
Time Complexity: O(n)
This means if you double the number of LEDs, the time to turn them all on roughly doubles.
[X] Wrong: "Turning on multiple LEDs happens all at once, so time stays the same no matter how many LEDs there are."
[OK] Correct: Each LED needs its own method call, so the total time adds up with more LEDs.
Understanding how loops over objects affect time helps you explain how your code scales when controlling hardware like LEDs.
What if we added a nested loop to blink each LED multiple times? How would the time complexity change?