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?

4
  • 1
    x is each value in to_visit iterable. min() computes key value for each value, returns value where key function has lowest value. Commented Dec 2, 2016 at 16:29
  • 1
    Does this answer solve your question? stackoverflow.com/a/18296814/406423 Commented Dec 2, 2016 at 16:30
  • It is iterating through all the items in path, passing the current item being visited as x and comparing to the next in path (as path[-1]) as to get the min distance. Commented Dec 2, 2016 at 16:34
  • @MadMike good find Commented Dec 2, 2016 at 16:34

1 Answer 1

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]).

Sign up to request clarification or add additional context in comments.

2 Comments

min returns the x element from to_visit having the lowest distance(path[-1], x), not the distance itself
Yes, you are right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.