Complete the code to create a vectorized version of the function square.
import numpy as np def square(x): return x ** 2 vectorized_square = np.vectorize([1]) result = vectorized_square(np.array([1, 2, 3])) print(result)
The np.vectorize() function takes a Python function as input and returns a vectorized version of it. Here, we pass the square function to vectorize it.
Complete the code to vectorize a function that returns 'even' or 'odd' for each number.
import numpy as np def even_or_odd(x): if x % 2 == 0: return 'even' else: return 'odd' vec_func = np.vectorize([1]) result = vec_func(np.array([1, 2, 3, 4])) print(result)
We pass the custom function even_or_odd to np.vectorize() to create a vectorized version that works element-wise on arrays.
Fix the error in the code by filling the blank to correctly vectorize the function add_one.
import numpy as np def add_one(x): return x + 1 vec_add_one = np.vectorize([1]) arr = np.array([10, 20, 30]) result = vec_add_one(arr) print(result)
You must pass the function object add_one without calling it (no parentheses) to np.vectorize().
Fill both blanks to create a vectorized function that returns True if a number is greater than 5 and False otherwise.
import numpy as np def greater_than_five(x): return x [1] 5 vec_func = np.vectorize(greater_than_five) arr = np.array([3, 6, 9]) result = vec_func(arr) == [2] print(result)
The function checks if x > 5. The vectorized function returns boolean values. We compare the result to True to confirm the condition.
Fill all three blanks to create a vectorized function that returns the length of a string if it is longer than 3 characters, else returns 0.
import numpy as np def length_if_long(word): return len(word) if len(word) [1] 3 else [2] vec_length = np.vectorize([3]) words = np.array(['cat', 'elephant', 'dog']) result = vec_length(words) print(result)
The function returns the length of the word if its length is greater than 3, otherwise returns 0. We vectorize the function by passing its name to np.vectorize().