0
0
Raspberry Piprogramming~5 mins

LED class and methods in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: LED class and methods
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling turn_on method on each LED object.
  • How many times: Once for each LED in the list (5 times in this example).
How Execution Grows With Input

As the number of LEDs increases, the number of times we call turn_on grows the same way.

Input Size (n)Approx. Operations
1010 calls to turn_on
100100 calls to turn_on
10001000 calls to turn_on

Pattern observation: The work grows directly with the number of LEDs.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of LEDs, the time to turn them all on roughly doubles.

Common Mistake

[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.

Interview Connect

Understanding how loops over objects affect time helps you explain how your code scales when controlling hardware like LEDs.

Self-Check

What if we added a nested loop to blink each LED multiple times? How would the time complexity change?