Polymorphism through functions in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Let's explore how the time needed to run a function changes when it can work with different types of inputs.
We want to see how the function's work grows as the input size grows.
Analyze the time complexity of the following code snippet.
def process(items):
result = []
for item in items:
result.append(str(item))
return result
values = [1, 2, 3, 4, 5]
print(process(values))
This function takes a list of items and converts each item to a string, collecting the results.
- Primary operation: Looping through each item in the input list.
- How many times: Once for every item in the list.
As the list gets bigger, the function does more work by converting more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions |
| 100 | 100 conversions |
| 1000 | 1000 conversions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Polymorphism makes the function slower because it handles different types."
[OK] Correct: The function still processes each item once; the type difference does not add extra loops or steps.
Understanding how functions handle different inputs without extra cost shows you know how to write flexible and efficient code.
"What if the function called another function inside the loop that itself loops over the item? How would the time complexity change?"
Practice
What does polymorphism through functions mean in Python?
Solution
Step 1: Understand polymorphism concept
Polymorphism means one function can handle different types of inputs.Step 2: Relate to function behavior
In Python, a single function can accept various data types and behave accordingly.Final Answer:
A single function works with different data types -> Option DQuick Check:
Polymorphism = single function, many types [OK]
- Confusing polymorphism with function overloading
- Believing functions accept only one data type
- Mixing polymorphism with inheritance
Which of the following is the correct way to check a variable's type inside a function for polymorphism?
def process(value):
# What to use here?
passSolution
Step 1: Recall Python type checking methods
Using isinstance() is the recommended way to check type in Python.Step 2: Compare options
if isinstance(value, int): uses isinstance(value, int), which correctly checks if value is an int or subclass.Final Answer:
if isinstance(value, int): -> Option CQuick Check:
Use isinstance() for type checks [OK]
- Using 'type() == int' which fails with subclasses
- Using 'is' or '==' incorrectly for type comparison
- Not checking type at all
What is the output of this code?
def describe(value):
if isinstance(value, int):
return f"Integer: {value}"
elif isinstance(value, str):
return f"String: {value}"
else:
return "Unknown type"
print(describe(10))
print(describe('hello'))
print(describe(3.14))Solution
Step 1: Check input 10
10 is int, so returns 'Integer: 10'.Step 2: Check input 'hello'
'hello' is str, so returns 'String: hello'.Step 3: Check input 3.14
3.14 is float, not int or str, so returns 'Unknown type'.Final Answer:
Integer: 10 String: hello Unknown type -> Option AQuick Check:
Type checks match outputs [OK]
- Assuming float is handled like int or str
- Ignoring else case output
- Mixing output order
Find the error in this polymorphic function and fix it:
def process(value):
if isinstance(value, int):
return value * 2
elif isinstance(value, str):
return value + value
else:
return value / 2
print(process('abc'))
print(process([1, 2, 3]))Solution
Step 1: Analyze input 'abc'
String input returns 'abcabc' by concatenation, no error.Step 2: Analyze input [1, 2, 3]
List input goes to else: value / 2, but dividing list by 2 causes TypeError.Step 3: Fix the error
Need to add a check for list type or avoid dividing list by 2.Final Answer:
Error: Cannot divide list by 2; fix by handling list separately -> Option BQuick Check:
List / 2 causes error [OK]
- Assuming all types support division
- Not testing with different input types
- Ignoring TypeError exceptions
Write a polymorphic function combine that accepts either two strings or two lists and returns their concatenation. What is the output of this code?
def combine(a, b):
if isinstance(a, str) and isinstance(b, str):
return a + b
elif isinstance(a, list) and isinstance(b, list):
return a + b
else:
return None
print(combine('Hi, ', 'there!'))
print(combine([1, 2], [3, 4]))
print(combine('Hello', [1, 2]))Solution
Step 1: Check first call combine('Hi, ', 'there!')
Both are strings, so returns concatenation 'Hi, there!'.Step 2: Check second call combine([1, 2], [3, 4])
Both are lists, so returns concatenated list [1, 2, 3, 4].Step 3: Check third call combine('Hello', [1, 2])
Types differ, so returns None.Final Answer:
'Hi, there!' [1, 2, 3, 4] None -> Option AQuick Check:
Type checks control output [OK]
- Not checking both inputs' types
- Trying to combine different types directly
- Returning wrong default for mismatched types
