Bird
Raised Fist0
NumPydata~20 mins

np.vectorize() for custom functions in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Vectorize Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of vectorized custom function with conditional logic
What is the output of this code that uses np.vectorize() on a custom function with a condition?
NumPy
import numpy as np

def classify(x):
    if x > 0:
        return 'pos'
    elif x < 0:
        return 'neg'
    else:
        return 'zero'

vec_classify = np.vectorize(classify)
arr = np.array([-2, 0, 3])
result = vec_classify(arr)
print(result)
A['zero' 'neg' 'pos']
B['neg' 'pos' 'zero']
C['pos' 'zero' 'neg']
D['neg' 'zero' 'pos']
Attempts:
2 left
💡 Hint
Think about how the function classifies negative, zero, and positive numbers.
❓ data_output
intermediate
2:00remaining
Resulting array shape after vectorizing a function returning tuples
What is the shape of the output array when applying np.vectorize() to a function that returns a tuple for each input element?
NumPy
import numpy as np

def to_pair(x):
    return (x, x**2)

vec_to_pair = np.vectorize(to_pair)
arr = np.array([1, 2, 3])
result = vec_to_pair(arr)
print(result.shape)
A(2, 3)
B(3, 2)
C(3,)
D(2,)
Attempts:
2 left
💡 Hint
Check what type of array is returned when the function returns tuples.
🔧 Debug
advanced
2:00remaining
Identify the error in vectorizing a function with multiple arguments
What error does this code raise when using np.vectorize() on a function with two arguments but passing only one array?
NumPy
import numpy as np

def add(x, y):
    return x + y

vec_add = np.vectorize(add)
arr = np.array([1, 2, 3])
result = vec_add(arr)
print(result)
ATypeError: add() missing 1 required positional argument: 'y'
BNo error, outputs [2 4 6]
CSyntaxError: invalid syntax
DValueError: operands could not be broadcast together
Attempts:
2 left
💡 Hint
Check how many arguments the function expects versus how many are passed.
🚀 Application
advanced
2:00remaining
Using np.vectorize to apply a function that returns different types
What is the output of this code where the vectorized function returns either int or str based on input?
NumPy
import numpy as np

def process(x):
    if x % 2 == 0:
        return x // 2
    else:
        return 'odd'

vec_process = np.vectorize(process)
arr = np.array([1, 2, 3, 4])
result = vec_process(arr)
print(result)
A['odd' '1' 'odd' '2']
B['odd' 1 'odd' 2]
C['odd' '1' 'odd' 2]
D['odd' 1 'odd' '2']
Attempts:
2 left
💡 Hint
Consider how numpy arrays handle mixed types in vectorized functions.
🧠 Conceptual
expert
2:00remaining
Why use np.vectorize instead of a for loop for custom functions?
Which statement best explains the main advantage of using np.vectorize() over a Python for loop when applying a custom function to a numpy array?
Anp.vectorize allows applying functions element-wise with numpy syntax but does not guarantee speed improvement.
Bnp.vectorize automatically converts the function to use GPU acceleration.
Cnp.vectorize provides true parallel execution and speeds up computation significantly.
Dnp.vectorize compiles the function to machine code for faster execution.
Attempts:
2 left
💡 Hint
Think about what np.vectorize actually does under the hood.

Practice

(1/5)
1. What is the main purpose of np.vectorize() in numpy?
easy
A. To apply a custom function element-wise on numpy arrays without explicit loops
B. To create random numbers in numpy arrays
C. To sort numpy arrays quickly
D. To reshape numpy arrays into different dimensions

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    To apply a custom function element-wise on numpy arrays without explicit loops -> Option A
  4. Quick Check:

    np.vectorize() = element-wise function application [OK]
Hint: Remember: vectorize applies functions element-wise on arrays [OK]
Common Mistakes:
  • Confusing vectorize with random number generation
  • Thinking vectorize reshapes arrays
  • Assuming vectorize sorts arrays
2. Which of the following is the correct way to create a vectorized version of a function f using numpy?
easy
A. vfunc = np.vectorize[f]
B. vfunc = np.vectorize(f)
C. vfunc = np.vectorize.f()
D. vfunc = np.vectorize->f

Solution

  1. Step 1: Recall the syntax of np.vectorize

    The correct syntax is to call np.vectorize as a function with the target function as argument: np.vectorize(f).
  2. 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.
  3. Final Answer:

    vfunc = np.vectorize(f) -> Option B
  4. Quick Check:

    Correct syntax uses parentheses: np.vectorize(f) [OK]
Hint: Use parentheses, not brackets or dots, with np.vectorize [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Trying to access vectorize as an attribute
  • Using invalid arrow syntax
3. What will be the output of the following code?
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)
medium
A. [2 5 10]
B. [1 4 9]
C. [2 3 4]
D. [1 2 3]

Solution

  1. Step 1: Understand the function logic

    The function square_plus_one returns x**2 + 1. For inputs 1, 2, 3, the outputs are 1^2+1=2, 2^2+1=5, 3^2+1=10.
  2. Step 2: Apply vectorized function on array

    Using np.vectorize, the function applies element-wise on the array [1, 2, 3], producing [2, 5, 10].
  3. Final Answer:

    [2 5 10] -> Option A
  4. Quick Check:

    Element-wise square plus one = [2 5 10] [OK]
Hint: Apply function to each element, then collect results [OK]
Common Mistakes:
  • Forgetting to add 1 after squaring
  • Confusing output with input array
  • Assuming vectorize changes function logic
4. Identify the error in this code snippet:
import numpy as np
def add_five(x):
    return x + 5
vfunc = np.vectorize(add_five)
arr = [1, 2, 3]
result = vfunc(arr)
print result
medium
A. np.vectorize cannot be used with functions that add numbers
B. The function add_five should return x * 5 instead of x + 5
C. The print statement is missing parentheses
D. The input array should be a numpy array, not a list

Solution

  1. Step 1: Check the print statement syntax

    In Python 3, print is a function and requires parentheses like print(result). print result causes a SyntaxError.
  2. 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.
  3. Final Answer:

    The print statement is missing parentheses -> Option C
  4. Quick Check:

    print requires parentheses in Python 3 [OK]
Hint: print requires parentheses in Python 3 [OK]
Common Mistakes:
  • Forgetting parentheses on print statement
  • Assuming list input is invalid for vectorize
  • Changing function logic unnecessarily
5. You want to apply a custom function that returns 'even' if a number is even and 'odd' if it is odd, on a numpy array. Which code correctly uses 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?
hard
A. result = np.apply_along_axis(even_odd, 1, arr) print(result)
B. result = even_odd(arr) print(result)
C. vfunc = np.vectorize(even_odd) result = even_odd(arr.tolist()) print(result)
D. vfunc = np.vectorize(even_odd) result = vfunc(arr) print(result)

Solution

  1. Step 1: Vectorize the custom function

    Use np.vectorize(even_odd) to create a vectorized version that works element-wise on arrays.
  2. Step 2: Apply vectorized function on numpy array

    Call the vectorized function with the numpy array arr to get the result array of 'even'/'odd' strings.
  3. Step 3: Check other options

    result = even_odd(arr) print(result) fails because even_odd does not support array input directly. vfunc = np.vectorize(even_odd) result = even_odd(arr.tolist()) print(result) fails because even_odd does not support list input. result = np.apply_along_axis(even_odd, 1, arr) print(result) fails with axis out of bounds for 1D array.
  4. Final Answer:

    vfunc = np.vectorize(even_odd) result = vfunc(arr) print(result) -> Option D
  5. Quick Check:

    Vectorize then apply on numpy array = vfunc = np.vectorize(even_odd) result = vfunc(arr) print(result) [OK]
Hint: Vectorize first, then apply on numpy array directly [OK]
Common Mistakes:
  • Calling function directly on array without vectorize
  • Calling non-vectorized function on list input
  • Using invalid axis in apply_along_axis
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard