0
0
NumPydata~10 mins

np.linalg.norm() for vector norms in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the Euclidean norm of vector v.

NumPy
import numpy as np
v = np.array([3, 4])
norm = np.linalg.norm([1])
print(norm)
Drag options to blanks, or click blank then click option'
Anp.linalg
B[3, 4]
Cnp.array([3, 4])
Dv
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the numpy module instead of the vector.
Passing a list instead of the numpy array variable.
2fill in blank
medium

Complete the code to calculate the 1-norm (sum of absolute values) of vector x.

NumPy
import numpy as np
x = np.array([-1, 2, -3])
norm_1 = np.linalg.norm(x, ord=[1])
print(norm_1)
Drag options to blanks, or click blank then click option'
A2
Bnp.inf
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using ord=2 which is the default Euclidean norm.
Using ord=0 which is not a valid norm for vectors.
3fill in blank
hard

Fix the error in the code to correctly compute the infinity norm (max absolute value) of vector y.

NumPy
import numpy as np
y = np.array([1, -5, 3])
norm_inf = np.linalg.norm(y, ord=[1])
print(norm_inf)
Drag options to blanks, or click blank then click option'
Ainf
Bnp.inf
Cfloat('inf')
Dinfinity
Attempts:
3 left
💡 Hint
Common Mistakes
Using string 'inf' instead of np.inf.
Using float('inf') which is not accepted here.
4fill in blank
hard

Fill both blanks to create a dictionary of vector norms for each vector in the list.

NumPy
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)
Drag options to blanks, or click blank then click option'
Ai
B0
C1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed index instead of the loop variable.
Using an invalid norm order.
5fill in blank
hard

Fill all three blanks to create a dictionary of Euclidean norms for vectors longer than 2 elements.

NumPy
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)
Drag options to blanks, or click blank then click option'
Ai
B2
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using different indices for vector access and length check.
Using wrong norm order.