Real-world modeling using objects in Python - Time & Space Complexity
When we model real-world things using objects in code, we often create and use many objects. Understanding how the time to run our program grows as we add more objects helps us write better programs.
We want to know: How does the time needed change when we have more objects to work with?
Analyze the time complexity of the following code snippet.
class Car:
def __init__(self, model):
self.model = model
cars = []
n = 10 # Example value for n
for i in range(n):
cars.append(Car(f"Model-{i}"))
for car in cars:
print(car.model)
This code creates a list of car objects and then prints the model of each car.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and printing each car object.
- How many times: Each operation happens once for every car, so n times.
As the number of cars (n) grows, the program does more work creating and printing each car.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 creates + 10 prints) |
| 100 | About 200 (100 creates + 100 prints) |
| 1000 | About 2000 (1000 creates + 1000 prints) |
Pattern observation: The total work grows directly with the number of cars. Double the cars, double the work.
Time Complexity: O(n)
This means the time to run the program grows in a straight line with the number of objects we create and use.
[X] Wrong: "Creating many objects is instant and does not affect time."
[OK] Correct: Each object takes time to create and use, so more objects mean more time needed.
Understanding how your program's time grows when using many objects shows you can think about efficiency in real-world coding. This skill helps you write clear and fast programs.
"What if we added a nested loop to compare every car with every other car? How would the time complexity change?"