3

I would like to sort the labeled points from closest to farthest to make my own knn:

def knn_classify(k, labeled_points, new_point):
  """chaque point labelisé devrait être une paire (point, label)"""

  # ordonne les points labelisés du plus proche au plus lointain
  by_distance = sorted(labeled_points, key= lambda (point, _): distance(point, new_point))
  
  # trouve les labels pour les k les plus proches
  k_nearest_labels = [label for _, label in by_distance[:k]]

  # et les faire voter
  return majority_vote(k_nearest_labels)

However, I have a problem with this:

by_distance = sorted(labeled_points, key= lambda (point, _): distance(point, new_point))

Indeed, it tells me that:

by_distance = sorted(labeled_points, key = lambda (point, _): distance(point, new_point))
                                                      ^
SyntaxError: invalid syntax
Revolucion for Monica
  • 2,848
  • 8
  • 39
  • 78
  • 1
    Tuple arguments were removed in Python 3 - they complicated introspection and didn't add enough to be worthwhile. – user2357112 Apr 10 '21 at 16:53
  • Does this answer your question? [Python lambda does not accept tuple argument](https://stackoverflow.com/questions/11328312/python-lambda-does-not-accept-tuple-argument) – Shiva Apr 10 '21 at 16:53
  • @user2357112supportsMonica O.o that's sad. And is there way around? – Revolucion for Monica Apr 10 '21 at 16:54
  • Tuple arguments aren't supported in Python 3 - you can adapt your key via indexing as follow: `key = lambda labelled_point: distance(labelled_point[0], new_point)` – Anson Miu Apr 10 '21 at 16:55
  • 1
    You can always `def` a function and pass the function directly to key, `key=my_func` if you had logic that was unclear in the `lambda`. – Henry Ecker Apr 10 '21 at 16:57

0 Answers0