Python on Raspberry Pi - Time & Space Complexity
When running Python code on a Raspberry Pi, it is important to understand how the time it takes to run your program grows as your input gets bigger.
We want to know how the program's running time changes when we give it more data to work with.
Analyze the time complexity of the following code snippet.
def sum_numbers(numbers):
total = 0
for num in numbers:
total += num
return total
nums = list(range(1, 101))
print(sum_numbers(nums))
This code adds up all the numbers in a list and prints the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list to add it to the total.
- How many times: Once for every number in the list.
As the list gets longer, the program takes longer because it adds more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the size of the input list.
Time Complexity: O(n)
This means the time to run the program grows in a straight line as the input list gets bigger.
[X] Wrong: "The program runs in the same time no matter how many numbers are in the list."
[OK] Correct: Because the program adds each number one by one, more numbers mean more work and more time.
Understanding how loops affect running time helps you explain your code clearly and shows you can think about efficiency, a skill useful in many programming tasks.
"What if we changed the list to a nested list and summed all numbers inside? How would the time complexity change?"