0
0
Pythonprogramming~5 mins

Enclosing scope in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enclosing scope
O(n)
Understanding Time Complexity

Let's explore how the time it takes to run code changes when we use variables from an enclosing scope inside a function.

We want to see how this affects the speed as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def multiplier(factor):
    def multiply(number):
        return number * factor
    return multiply

times3 = multiplier(3)
result = times3(10)

This code creates a function that remembers a number from outside and uses it to multiply another number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here; the multiply function just does one multiplication.
  • How many times: The multiplication happens once per call to the inner function.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 multiplications if called 10 times
100100 multiplications if called 100 times
10001000 multiplications if called 1000 times

Pattern observation: The time grows directly with how many times you call the inner function, not because of the enclosing scope.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of times you use the inner function.

Common Mistake

[X] Wrong: "Using variables from outside the function makes the code slower for each call."

[OK] Correct: The inner function just uses the remembered value directly; it doesn't add extra loops or steps, so speed depends on how many times you call it, not on the enclosing scope.

Interview Connect

Understanding how functions remember outside values helps you write clear and efficient code, a skill that shows you know how to manage data and speed well.

Self-Check

"What if the inner function had a loop inside it? How would the time complexity change?"