How to associate objects to the vertices of a graph?
I am studying about graph theory, more specifically about the vertices which are units that represent a given node of a graph. However, there are still some doubts regarding vertices.
See this illustration graph in Python:
graph = {
'A': ['B', 'C', 'D'],
'B': ['A'],
'C': ['A', 'D'],
'D': ['A', 'C']
}
Notice that it is an undirected graph, the dictionary saves the path for each vertex.
My doubt is related to the vertex, if it is possible to make it represent a object or a class. And the object I would like my Vertex to represent would be of the class type Ambiente
:
class Ambiente:
def __init__(self, titulo, descricao, id):
self.titulo = titulo
self.descricao = descricao
self.id = id
I tried to associate the index in the dictionary:
ambientes = {
'A': Ambiente('Sala de maquinas',
"A sala contém várias maquinas industriais, todas parecem não funcionar por anos. O som que é emitido dela é fantasmagórico e causa um estado de panico e alerta, como se a qualquer momento alguma entidade fosse emergir daquela pilha de metal amaldiçoada. Há poucos ruídos, no entanto, não há sinal de vida alguma.",
'A'
)
}
But it seems to me not to be effective in this way, even more so when I am going to need to navigate the paths of the graph. Therefore, I would like my question below to be answered.
Question
How could I associate objects to the vertices of the graph?
2 answers
See if you like this solution:
class Ambiente:
def __init__(self, titulo, descricao, id):
self.titulo = titulo
self.descricao = descricao
self.id = id
A = Ambiente('Sala de maquinas',
"A sala contém várias maquinas industriais e bla bla bla",
'A'
)
B = Ambiente('Salão de Festas',
"Só fica quem sabe dançar, beber e se divertir!!",
'B'
)
C = Ambiente('Banheiro',
"J-a escovou os dentes antes de dormir?",
'C'
)
D = Ambiente('Jardim',
"Não coma muitos desses cogumelos ou você terá alucinações...",
'D'
)
grafo = {
A: [B, C, D],
B: [A],
C: [A, D],
D: [A, C]
}
Now we have a graph with objects of type environment, not just strings. We can even make a function: (Edit: following Isac's suggestion)
def printa_grafo(grafo):
print ("{")
for key, value in grafo.items():
print(" {}: [{}]".format(key.id, ', '.join(map(lambda x: x.id, value))))
print ("}")
>>> printa_grafo(grafo)
{
B: [A]
D: [A, C]
A: [B, C, D]
C: [A, D]
}
Good Night friend.
From start you are trying to reference a non-instantiated class, what can be done about this is you instantiate that class into a variable and then use that variable as the "value" of a key in that Dictionary of the graph.
More or less like this
class Ambiente:
def __init__(self, titulo, descricao, id):
self.titulo = titulo
self.descricao = descricao
self.id = id
def __str__(self):
return "%s, %s, %s" % self.titulo,self.descricao,self.id
Instantiating the Class:
verticeAmbiente = Ambiente('Sala de maquinas',
"A sala contém várias maquinas industriais, todas parecem não funcionar por anos. O som que é emitido dela é fantasmagórico e causa um estado de panico e alerta, como se a qualquer momento alguma entidade fosse emergir daquela pilha de metal amaldiçoada. Há poucos ruídos, no entanto, não há sinal de vida alguma.",
'A')
After:
Ambiente = {'A': verticeAmbiente}
Since the __str__
method has been implemented within the class, it prints all the attributes of the object passed no builder.
If you want to see, just:
print(Ambiente['A'])
In "tea", (because I never needed it like that)
But I hope it helps.
Reference https://penseallen.github.io/PensePython2e/17-classes-metodos.html