I want it to return true if there is a cycle and false if there is not. It works if there is only one edge per node...
eg:
walkways_info = """\
U 3
0 1
1 2
2 0
"""'
print(interesting_path_feasible(walkways_info))
But it doesn't work when there are multiple edges per node as the dictionary doesn't hold multiple values.
eg:
walkways_info = """\
U 7
1 2
1 5
1 6
2 3
2 5
3 4
4 5
"""
How would I fix this? Thanks in advance :)
def interesting_path_feasible(walkways_info_str):
"""Determines if a cycle exists"""
graph_dict = dict(e.split(' ') for e in walkways_info_str.splitlines())
visited = set()
path = [object()]
path_set = set(path)
stack = [iter(graph_dict)]
while stack:
for node in stack[-1]:
if node in path_set:
return True
elif node not in visited:
visited.add(node)
path.append(node)
path_set.add(node)
stack.append(iter(graph_dict.get(node, ())))
break
else:
path_set.remove(path.pop())
stack.pop()
return False