I need to implement an algorithm such that in a collection of unique and ordered graph edges, I can find a cyclic node.
E.g. for a ->b, b->c, c->a
, then 'a'
is a cyclic node and thus I want to annotate it in this edge with 'a@'
and simillar for others.
As example data I use this:
a = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('a', 'e'), ('e', 'a'), ('f', 'e')]
Then this would become:
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a@'), ('a', 'e'), ('e', 'a@'), ('f', 'e')]
How can I achieve this in python?
This is what I tried:
collection = {}
data, result = [], []
for i, j in a:
if i in collection.keys():
collection[i].append(j)
else:
collection[i] = [j]
if j in collection.keys():
for item in range(len(collection[i])):
if collection[i][item] == j:
nr += 1
collection[i][item] = j + '@'
print(collection)
It seems to work for cycles but it also takes into account strong connected components that are not cycles.. So I am looking for something similar like networkx simple cycles (no subcycles), also I need data returned in this way like above.