np.vectorize() for custom functions in NumPy - Time & Space Complexity
We want to understand how the time it takes to run a custom function on many numbers changes when using np.vectorize().
How does the work grow when we apply the function to bigger arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
def my_func(x):
return x ** 2 + 1
n = 10
vec_func = np.vectorize(my_func)
arr = np.arange(n)
result = vec_func(arr)
This code applies a custom function to each element of an array using np.vectorize.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying
my_functo each element of the array. - How many times: Once for each element in the input array (n times).
As the array size grows, the function runs once per element, so the total work grows in direct proportion to the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: Doubling the input size roughly doubles the work done.
Time Complexity: O(n)
This means the time to run grows linearly with the number of elements in the array.
[X] Wrong: "np.vectorize makes the function run faster by doing things all at once like built-in numpy operations."
[OK] Correct: np.vectorize is a convenience tool that still calls the function once per element in Python, so it does not speed up the function itself.
Understanding how np.vectorize works helps you explain performance when using custom functions on arrays, a useful skill for data tasks and coding interviews.
What if we replaced np.vectorize with a true numpy ufunc? How would the time complexity change?
Practice
np.vectorize() in numpy?Solution
Step 1: Understand the role of
np.vectorize()np.vectorize()takes a function that works on single values and makes it work on arrays element-wise.Step 2: Compare with other numpy functions
It is not used for random number generation, sorting, or reshaping arrays, which are handled by other numpy functions.Final Answer:
To apply a custom function element-wise on numpy arrays without explicit loops -> Option AQuick Check:
np.vectorize() = element-wise function application [OK]
- Confusing vectorize with random number generation
- Thinking vectorize reshapes arrays
- Assuming vectorize sorts arrays
f using numpy?Solution
Step 1: Recall the syntax of np.vectorize
The correct syntax is to callnp.vectorizeas a function with the target function as argument:np.vectorize(f).Step 2: Check the other options for syntax errors
Options A, C, and D use incorrect syntax like square brackets, dot notation, or arrows which are invalid in Python.Final Answer:
vfunc = np.vectorize(f) -> Option BQuick Check:
Correct syntax uses parentheses: np.vectorize(f) [OK]
- Using square brackets instead of parentheses
- Trying to access vectorize as an attribute
- Using invalid arrow syntax
import numpy as np
def square_plus_one(x):
return x**2 + 1
vfunc = np.vectorize(square_plus_one)
arr = np.array([1, 2, 3])
result = vfunc(arr)
print(result)Solution
Step 1: Understand the function logic
The functionsquare_plus_onereturnsx**2 + 1. For inputs 1, 2, 3, the outputs are 1^2+1=2, 2^2+1=5, 3^2+1=10.Step 2: Apply vectorized function on array
Usingnp.vectorize, the function applies element-wise on the array[1, 2, 3], producing[2, 5, 10].Final Answer:
[2 5 10] -> Option AQuick Check:
Element-wise square plus one = [2 5 10] [OK]
- Forgetting to add 1 after squaring
- Confusing output with input array
- Assuming vectorize changes function logic
import numpy as np
def add_five(x):
return x + 5
vfunc = np.vectorize(add_five)
arr = [1, 2, 3]
result = vfunc(arr)
print resultSolution
Step 1: Check the print statement syntax
In Python 3,printis a function and requires parentheses likeprint(result).print resultcauses a SyntaxError.Step 2: Verify other parts of the code
The function logic is correct, np.vectorize works fine with addition functions, and input lists are accepted by np.vectorize.Final Answer:
The print statement is missing parentheses -> Option CQuick Check:
print requires parentheses in Python 3 [OK]
- Forgetting parentheses on print statement
- Assuming list input is invalid for vectorize
- Changing function logic unnecessarily
np.vectorize() to achieve this?def even_odd(x):
if x % 2 == 0:
return 'even'
else:
return 'odd'
arr = np.array([1, 2, 3, 4])
# What next?Solution
Step 1: Vectorize the custom function
Usenp.vectorize(even_odd)to create a vectorized version that works element-wise on arrays.Step 2: Apply vectorized function on numpy array
Call the vectorized function with the numpy arrayarrto get the result array of 'even'/'odd' strings.Step 3: Check other options
result = even_odd(arr) print(result) fails becauseeven_odddoes not support array input directly. vfunc = np.vectorize(even_odd) result = even_odd(arr.tolist()) print(result) fails becauseeven_odddoes not support list input. result = np.apply_along_axis(even_odd, 1, arr) print(result) fails with axis out of bounds for 1D array.Final Answer:
vfunc = np.vectorize(even_odd) result = vfunc(arr) print(result) -> Option DQuick Check:
Vectorize then apply on numpy array = vfunc = np.vectorize(even_odd) result = vfunc(arr) print(result) [OK]
- Calling function directly on array without vectorize
- Calling non-vectorized function on list input
- Using invalid axis in apply_along_axis
Ready to prove it?
Pass the test and this pattern moves unknown
