All problems
Distance-Weighted KNN Vote
Problem
Predict a label by distance-weighted k-nearest-neighbor voting using Euclidean distance. Weight each neighbor by 1/d; if a zero distance is found, immediately return that neighbor's label.
Ties are broken by the smallest label. If there are no neighbors to vote, return None.
Hint
Nearer neighbors get larger 1/d weights; an exact match short-circuits the vote.
Test cases
case 1
in: [[[0],[1],[3]],["a","b","b"],[0.5],3]
expected: "b"
case 2
in: [[[1],[2]],[5,9],[1],2]
expected: 5
case 3
in: [[[0],[10]],[1,2],[1],1]
expected: 1
case 4
in: [[],[],[0],1]
expected: null
Starter codePython
def knn_weighted_vote(X_train, y_train, x_test, k):
# Your code here
pass4 test cases · run your code against them in the editor