0
0
Raspberry Piprogramming~5 mins

Python on Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Python on Raspberry Pi
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets longer, the program takes longer because it adds more numbers one by one.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The number of operations grows directly with the size of the input list.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the program grows in a straight line as the input list gets bigger.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we changed the list to a nested list and summed all numbers inside? How would the time complexity change?"