Button class with callbacks in Raspberry Pi - Time & Space 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.
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 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.
Each time the button is pressed, the program runs all callbacks one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 callbacks | 10 calls to callback functions |
| 100 callbacks | 100 calls to callback functions |
| 1000 callbacks | 1000 calls to callback functions |
Pattern observation: The work grows directly with the number of callbacks. More callbacks mean more work each press.
Time Complexity: O(n)
This means the time to handle a button press grows linearly with the number of callbacks attached.
[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.
Understanding how callbacks affect performance helps you design responsive programs and explain your code clearly in interviews.
"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?"