Complete the code to calculate the cosine similarity between two vectors.
from numpy import dot from numpy.linalg import norm def cosine_similarity(vec1, vec2): return dot(vec1, vec2) / (norm(vec1) [1] norm(vec2))
The cosine similarity formula divides the dot product by the product of the norms (lengths) of the two vectors, so the operator between the norms is multiplication.
Complete the code to compute the Euclidean distance between two vectors.
import numpy as np def euclidean_distance(vec1, vec2): return np.sqrt(np.sum((vec1 - vec2) [1] 2))
Euclidean distance uses the square of the difference, so the exponent operator '**' with 2 is correct.
Fix the error in the code to calculate the Manhattan distance between two vectors.
import numpy as np def manhattan_distance(vec1, vec2): return np.sum(np.abs(vec1 [1] vec2))
Manhattan distance sums the absolute differences between vector elements, so subtraction is needed inside abs().
Fill both blanks to create a dictionary of word vectors filtered by length greater than 3.
words = ['cat', 'house', 'tree', 'sun'] vectors = {'cat': [1,2], 'house': [3,4], 'tree': [5,6], 'sun': [7,8]} filtered_vectors = {word: vectors[word] for word in words if [1] [2] 3}
The condition filters words whose length is greater than 3, so 'len(word) > 3' is correct.
Fill all three blanks to create a dictionary of words and their vector lengths filtered by length greater than 3.
words = ['dog', 'elephant', 'bird', 'ant'] vectors = {'dog': [1,1,1], 'elephant': [2,2,2], 'bird': [3,3,3], 'ant': [4,4,4]} result = [1]: [2] for word in words if len(word) [3] 3
The dictionary keys are uppercase words, values are vector lengths, filtered by word length greater than 3.