0
0
NumPydata~10 mins

Broadcasting for distance matrices 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 create a 2D array of points using NumPy.

NumPy
import numpy as np
points = np.array([1])
Drag options to blanks, or click blank then click option'
A[[1, 2], [3, 4], [5, 6]]
B[(1, 2), (3, 4), (5, 6)]
C[1, 2, 3, 4]
D[1, 2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a flat list instead of a list of lists.
Using tuples inside the list without nesting.
2fill in blank
medium

Complete the code to calculate the difference between each point and all points using broadcasting.

NumPy
diff = points[:, np.newaxis, :] - [1]
Drag options to blanks, or click blank then click option'
Apoints
Bnp.array(points)
Cpoints.T
Dnp.newaxis
Attempts:
3 left
💡 Hint
Common Mistakes
Using transpose which changes shape incorrectly.
Using np.newaxis alone without the array.
3fill in blank
hard

Fix the error in the code to compute the squared distances between points.

NumPy
sq_dist = np.sum(diff[1]2, axis=2)
Drag options to blanks, or click blank then click option'
A//
B*
C**
D^
Attempts:
3 left
💡 Hint
Common Mistakes
Using '*' instead of '**' for squaring.
Summing along the wrong axis.
4fill in blank
hard

Complete the code to compute the Euclidean distance matrix from squared distances.

NumPy
dist_matrix = np.sqrt(sq_dist) + [1]
Drag options to blanks, or click blank then click option'
Bnp.zeros_like(sq_dist)
Cnp.ones_like(sq_dist)
Dnp.abs(sq_dist)
Attempts:
3 left
💡 Hint
Common Mistakes
Adding ones or absolute values which change the distances.
Adding unnecessary terms that distort results.
5fill in blank
hard

Fill all three blanks to create a dictionary of points with their distances greater than 2.

NumPy
dist_dict = {tuple(points[i]): dist_matrix[i, j] for i in range(len(points)) for j in range(len(points)) if dist_matrix[i, j] [1] 2 and i != j and tuple(points[j]) [2] dist_dict and dist_dict[tuple(points[j])] [3] dist_matrix[i, j]}
Drag options to blanks, or click blank then click option'
A>
Bin
C<
Dnot in
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for distance comparison.
Checking 'in' instead of 'not in' for dictionary keys.