2

I have the following code for a greedy implementation of the traveling salesman problem. I can't wrap my head around what exactly the lambda function does in this code.

def distance(p1, p2):
    return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5

def tsp_greedy(points, start=None):
    if start is None:
        start = points[0]
    to_visit = points
    path = [start]
    to_visit.remove(start)
    while to_visit:
        closest = min(to_visit, key=lambda x: distance(path[-1], x))
        path.append(closest)
        to_visit.remove(closest)
    return path

I realize it's creating an anonymous function which x gets passed into. But I'm not sure what is getting passed into this function. What is x?

123
  • 8,733
  • 14
  • 57
  • 99

1 Answers1

1

closest becomes to_visit[i] such that

distance(path[-1], to_visit[i]) = 
  min(distance(path[-1], to_visit[0]), distance(path[-1], to_visit[1]), ...)

In other words, the lambda function makes comparison not by to_visit[i] but by distance(path[-1], to_visit[i]).

Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23