MCPcopy Index your code
hub / github.com/jwasham/practice-python / contains_cycle

Method contains_cycle

graphs/directed_graph_list.py:110–145  ·  view source on GitHub ↗

Determines if one of the connected components contains a cycle :return: true if one of the connected components contains a cycle :rtype: bool

(self)

Source from the content-addressed store, hash-verified

108 return parents
109
110 def contains_cycle(self):
111 """
112 Determines if one of the connected components contains a cycle
113 :return: true if one of the connected components contains a cycle
114 :rtype: bool
115 """
116 contains_cycle = False
117 STATUS_STARTED = 1
118 STATUS_FINISHED = 2
119
120 for vertex in self.get_vertex():
121 statuses = {}
122 to_visit = [vertex]
123
124 while to_visit and not contains_cycle:
125 v = to_visit.pop()
126
127 if v in statuses:
128 if statuses[v] == STATUS_STARTED:
129 statuses[v] = STATUS_FINISHED
130 else:
131 statuses[v] = STATUS_STARTED
132 to_visit.append(v) # add to stack again to signal vertex has finished DFS
133
134 for u in self.get_neighbor(v):
135 if u in statuses:
136 if statuses[u] == STATUS_STARTED:
137 contains_cycle = True
138 break
139 else:
140 to_visit.append(u)
141
142 if contains_cycle:
143 break
144
145 return contains_cycle
146
147 def topological_sort(self):
148 """

Callers 3

topological_sortMethod · 0.95
test_contains_cycleFunction · 0.80

Calls 4

get_vertexMethod · 0.95
get_neighborMethod · 0.95
popMethod · 0.80
appendMethod · 0.80

Tested by 2

test_contains_cycleFunction · 0.64