Function definition and syntax in Python - Time & Space Complexity
When we write a function, it's important to know how long it takes to run as the input changes.
We want to see how the time grows when we call the function with bigger inputs.
Analyze the time complexity of the following code snippet.
def greet(name):
print(f"Hello, {name}!")
user_name = "Alice"
greet(user_name)
This code defines a simple function that prints a greeting message once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single print statement inside the function.
- How many times: The function runs once, so the print runs once.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the function takes the same amount of time no matter how big the input is.
[X] Wrong: "The function takes longer if the input name is longer."
[OK] Correct: The function just prints once, so the time does not grow with input size.
Understanding simple function time helps build a strong base for more complex code analysis.
"What if the function printed each character of the name one by one? How would the time complexity change?"