How to associate objects to the vertices of a graph?

Asked

Viewed 110 times

3

I’m studying about graph theory, more specifically about vertices which are units representing a given node of a graph. However, there are still some doubts regarding the vertices.

See this illustration graph in Python:

graph = {
  'A': ['B', 'C', 'D'],  
  'B': ['A'],
  'C': ['A', 'D'],
  'D': ['A', 'C']
}

Note that it is an undirected graph, the dictionary holds the path to 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 that I would like my vertex to represent would be the kind of class Ambiente:

class Ambiente:
  def __init__(self, titulo, descricao, id):
    self.titulo = titulo
    self.descricao = descricao
    self.id = id

I tried to associate the content 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 does not seem to be effective in this way, especially when I 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

2


See if this solution pleases you:

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 the suggestion of Isac)

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]
}
  • The for that builds the string is basically a join and can therefore be replaced by string += ', '.join(map(lambda x: x.id, value)). Personally I replace everything inside the first for by a single print, thus: print(" {}: [{}]".format(key.id, ', '.join(map(lambda x: x.id, value)))). In addition to the str which are also not necessary because key.id is already a string

  • @Isac, thanks for the suggestion :) . I even edited my reply.

1

Good night buddy.

At first, I was tempted to refer to a class that was not present, what can be done in this respect is to see this class in a variable and then use this variable as the "value" of a key in this dictionary of the Graph.

sort of 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')

Afterward:

Ambiente = {'A': verticeAmbiente}

How the method was implemented __str__ within the class, it prints all attributes of the object passed in the builder.

if you want to see:

print(Ambiente['A'])

In "tése", (especially because I’ve never needed it like this)

but I hope it helps.

reference https://penseallen.github.io/PensePython2e/17-classes-metodos.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.