1
I am creating a graph with the following rules:
- The graph is a dictionary.
- The vertices are the keys of this dictionary and the values are the edges.
- Since I can have more than one edge for a vertex, I need to create a set
set()
for the dictionary values.
The problem also says that the edges need to contain vertices and 'weights' and that it is therefore necessary to place them in tuples within this set.
I don’t know if it’s clear, but the implementation code for adding edges is as follows::
self.grafo
is the dictionary.vert_Origem
is 'Jim' - Jim is already a vertex included in the dictionaryvert_Destino
is 'Liam'
def addArestas (self, vert_Origem, vert_Destino, peso=1):
for key, value in self.grafo.items():
aresta= tuple()
aresta = (vert_Destino, peso)
value.add(aresta)
self.graph[vert_Origem] = aresta
return True
It turns out that it returns all keys with all edges. I’m not able to place the specific edges for each vertex.
When I put:
def addArestas (self, vert_Origem, vert_Destino, peso=1):
for key, value in self.grafo.items():
aresta= tuple()
aresta = (vert_Destino, peso)
conjunto = set()
conjunto.add(aresta)
self.graph[vert_Origem] = conjunto
return True
The method returns me only the last edge, overwriting the other entries.
Someone can identify the mistake?
Leafar, I get the logic, thank you. On the use of tuples in set(), you mean that if I have to change the weight of the edge I have to remove the current edge first before inserting the new one?
– Gabriel Moura
Yes, if you insert the tuple
(4, 5)
and then insert the tuple(4, 6)
, They’re both going to stay on set because they’re not exactly the same. What Voce can do is store only the destination node in the set, thus becoming a set of integers and not tuples. To store weights, Voce can create a new dictionarydict_pesos
that maps tuples with the nodes of each edge(nodo1, nodo2)
for the value of the corresponding weight.– Leafar