2

I'm doing a kind of Dijkstra as homework.
This is how the class Vertex looks.

class Vertex:
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.minDistance = float('inf')
        self.previousVertex = None

In other class I have a list of unvisited vertexes and I want to find a minimum distance, so I can recursively work with the Vertex having that minDistance.

e.g. unvisited = [Vertex1, Vertex2,...]

Tried to do it with for cycle, but by iterating it and saving it to a variable didn't work as it saved only the last value. How can I find a min value of a class atribute in list?

1 Answer 1

6

A more Pythonic one-liner:

minDistance = min(otherVertex.distance for otherVertex in unvisited)

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

6 Comments

As a complement to this, you can find the Vertex which has the minimum distance with minVertex = min(unvisited, key=operator.attrgetter('distance'))
Díky, co když mi to ale najde nekonečno jako minimum?
@AlessandroPetric: Please try to stick to English on StackOverflow.
Sorry, @ShadowRanger saw that the guy who answered is from Czech Republic, so I wrote it in czech. Anyway, it's working.
You have to take care about inf yourself - that depends on your application. In Dijkstra it could mean there are no adjacent vertices = abort search.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.