Complete the code to calculate the Euclidean norm of vector v.
import numpy as np v = np.array([3, 4]) norm = np.linalg.norm([1]) print(norm)
The function np.linalg.norm() calculates the length (norm) of the vector passed to it. Here, v is the vector.
Complete the code to calculate the 1-norm (sum of absolute values) of vector x.
import numpy as np x = np.array([-1, 2, -3]) norm_1 = np.linalg.norm(x, ord=[1]) print(norm_1)
The ord=1 argument tells np.linalg.norm() to compute the 1-norm, which is the sum of absolute values of the vector elements.
Fix the error in the code to correctly compute the infinity norm (max absolute value) of vector y.
import numpy as np y = np.array([1, -5, 3]) norm_inf = np.linalg.norm(y, ord=[1]) print(norm_inf)
np.inf.float('inf') which is not accepted here.The correct way to specify the infinity norm in np.linalg.norm() is ord=np.inf. Other options cause errors or are invalid.
Fill both blanks to create a dictionary of vector norms for each vector in the list.
import numpy as np vectors = [np.array([1, 2]), np.array([3, 4])] norms = {i: np.linalg.norm(vectors[[1]], ord=[2]) for i in range(len(vectors))} print(norms)
The loop variable i is used to index each vector in the list. Using ord=1 computes the 1-norm for each vector.
Fill all three blanks to create a dictionary of Euclidean norms for vectors longer than 2 elements.
import numpy as np vectors = [np.array([1, 2]), np.array([3, 4, 5]), np.array([6, 7, 8, 9])] norms = {i: np.linalg.norm(vectors[[1]], ord=[2]) for i in range(len(vectors)) if len(vectors[[3]]) > 2} print(norms)
The loop variable i (option A) is used to index vectors. The Euclidean norm is ord=2. The length check uses the same index i.