Duck typing concept in Python - Time & Space Complexity
When using duck typing, we want to know how the program's speed changes as we work with different objects.
We ask: How does the program handle operations on objects that behave similarly but may be different types?
Analyze the time complexity of the following code snippet.
def process_items(items):
for item in items:
item.quack()
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm pretending to be a duck!")
process_items([Duck(), Person(), Duck()])
This code calls the quack method on each object in a list, relying on duck typing to allow different types to respond similarly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item and calling
quack(). - How many times: Once for each item in the list.
Each item in the list causes one call to quack(). So, the work grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to quack() |
| 100 | 100 calls to quack() |
| 1000 | 1000 calls to quack() |
Pattern observation: The number of operations grows evenly as the list gets bigger.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the number of items you process.
[X] Wrong: "Duck typing makes the program slower because it checks types at runtime for every call."
[OK] Correct: The program just calls the method on each object without extra type checks; it trusts the object can respond, so the speed depends mainly on how many items you have.
Understanding how duck typing affects time helps you explain how flexible code runs as data grows, showing you grasp both design and performance.
"What if each quack() method took longer because it did more work? How would that affect the overall time complexity?"