0
0
Raspberry Piprogramming~5 mins

Button class with callbacks in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Button class with callbacks
O(n)
Understanding Time Complexity

When using a Button class with callbacks, it's important to understand how the program's work grows as more buttons or events are handled.

We want to know how the time to process button presses changes as the number of buttons or callbacks increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Button:
    def __init__(self):
        self.callbacks = []

    def add_callback(self, func):
        self.callbacks.append(func)

    def press(self):
        for callback in self.callbacks:
            callback()

This code defines a Button class that stores callback functions and calls each one when the button is pressed.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through all stored callbacks when the button is pressed.
  • How many times: Once per button press, the loop runs once for each callback added.
How Execution Grows With Input

Each time the button is pressed, the program runs all callbacks one by one.

Input Size (n)Approx. Operations
10 callbacks10 calls to callback functions
100 callbacks100 calls to callback functions
1000 callbacks1000 calls to callback functions

Pattern observation: The work grows directly with the number of callbacks. More callbacks mean more work each press.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle a button press grows linearly with the number of callbacks attached.

Common Mistake

[X] Wrong: "Adding more callbacks won't affect how long the button press takes."

[OK] Correct: Each callback runs in order, so more callbacks mean more work and longer time to finish.

Interview Connect

Understanding how callbacks affect performance helps you design responsive programs and explain your code clearly in interviews.

Self-Check

"What if the Button class stored callbacks in a tree structure and only called some of them on press? How would the time complexity change?"