Imported Upstream version 4.3.1
This commit is contained in:
@@ -1,10 +1,9 @@
|
||||
#
|
||||
# Copyright (C) 2015-2017 FreeIPA Contributors see COPYING for license
|
||||
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
|
||||
#
|
||||
from collections import deque
|
||||
|
||||
|
||||
class Graph(object):
|
||||
class Graph():
|
||||
"""
|
||||
Simple oriented graph structure
|
||||
|
||||
@@ -24,10 +23,8 @@ class Graph(object):
|
||||
def add_edge(self, tail, head):
|
||||
if tail not in self.vertices:
|
||||
raise ValueError("tail is not a vertex")
|
||||
|
||||
if head not in self.vertices:
|
||||
raise ValueError("head is not a vertex")
|
||||
|
||||
self.edges.append((tail, head))
|
||||
self._adj[tail].append(head)
|
||||
|
||||
@@ -36,27 +33,23 @@ class Graph(object):
|
||||
self.edges.remove((tail, head))
|
||||
except KeyError:
|
||||
raise ValueError(
|
||||
"graph does not contain edge: ({0}, {1})".format(tail, head)
|
||||
)
|
||||
"graph does not contain edge: (%s, %s)" % (tail, head))
|
||||
self._adj[tail].remove(head)
|
||||
|
||||
def remove_vertex(self, vertex):
|
||||
try:
|
||||
self.vertices.remove(vertex)
|
||||
except KeyError:
|
||||
raise ValueError(
|
||||
"graph does not contain vertex: {0}".format(vertex)
|
||||
)
|
||||
raise ValueError("graph does not contain vertex: %s" % vertex)
|
||||
|
||||
# delete _adjacencies
|
||||
del self._adj[vertex]
|
||||
for adj in self._adj.values():
|
||||
adj[:] = [v for v in adj if v != vertex]
|
||||
for key, _adj in self._adj.items():
|
||||
_adj[:] = [v for v in _adj if v != vertex]
|
||||
|
||||
# delete edges
|
||||
self.edges = [
|
||||
e for e in self.edges if vertex not in (e[0], e[1])
|
||||
]
|
||||
edges = [e for e in self.edges if e[0] != vertex and e[1] != vertex]
|
||||
self.edges[:] = edges
|
||||
|
||||
def get_tails(self, head):
|
||||
"""
|
||||
@@ -76,12 +69,11 @@ class Graph(object):
|
||||
Return a set of all visited vertices
|
||||
"""
|
||||
if not start:
|
||||
start = next(iter(self.vertices))
|
||||
start = list(self.vertices)[0]
|
||||
visited = set()
|
||||
queue = deque([start])
|
||||
|
||||
queue = [start]
|
||||
while queue:
|
||||
vertex = queue.popleft()
|
||||
vertex = queue.pop(0)
|
||||
if vertex not in visited:
|
||||
visited.add(vertex)
|
||||
queue.extend(set(self._adj.get(vertex, [])) - visited)
|
||||
|
||||
Reference in New Issue
Block a user