Skip to content

Instantly share code, notes, and snippets.

@hiagop
Created May 27, 2018 17:44
Show Gist options
  • Save hiagop/b1ee74cdf2448739408c7b42f78d35d5 to your computer and use it in GitHub Desktop.
Save hiagop/b1ee74cdf2448739408c7b42f78d35d5 to your computer and use it in GitHub Desktop.
A simple graphs object oriented implementation
class Node:
def __init__(self, name=None, value=None):
self.name = name
self.value = value
def __repr__(self):
return "Node (name={0}, value={1})".format(self.name, self.value)
def __str__(self):
return "{0}: {1}".format(self.name, self.value)
class Graph:
__vertices = set()
__edges = set()
def __init__(self, vertices=[], edges=[]):
for v in vertices:
self.__vertices.add(v)
for e in edges:
self.__edges.add(e)
def __repr__(self):
return "Graph (vertices={0!s}, edges={1!s})".format(*self.size())
def add_vertices(self, vertices=[]):
for v in vertices:
if v.name not in [sv.name for sv in self.__vertices]:
self.__vertices.update(set(vertices))
def add_edges(self, edges=[]):
names = [sv.name for sv in self.__vertices]
for e in edges:
if e[0] in names:
if e[1] in names:
self.__edges.add(e)
else:
print("can't add edge. no vertex named %s" % e[1])
else:
print("can't add edge. no vertex named %s" % e[0])
del(names)
def get_vertices(self):
return self.__vertices
def get_edges(self):
return self.__edges
def size(self):
return len(self.__vertices), len(self.__edges)
@willianrocha
Copy link

Poderias implementar um overload no __eq__, __ne__ e __hash__. Assim, tu podes simplesmente dar um update() sem se preucupar com os tratamentos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment