How can I label a node that is the initial vertex in a cycle from graph data

2024/11/16 7:37:07

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.

Answer

This solution builds all possible paths that it encounters in the edge list, since we don't really know where a cycle starts. It also prunes the path list that it creates to prevent some memory bloat if your graph is large. It is ugly but works based on your needs.

a = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'), ('a', 'e'), ('e', 'a'), ('f', 'e')]annotated = []
paths = []
for edge in a:new_paths = []paths.append(''.join(edge))annotated.append(edge)cycle = ''for path in paths[:]:if path.endswith(edge[0]):if path.startswith(edge[1]):annotated[-1] = (annotated[-1][0], annotated[-1][1]+'@')cycle = path + edge[1]else:new_paths.append(path + edge[1])else:new_paths.append(path)paths = [x for x in new_paths if x not in cycle]print(paths)
print(f'Result: {annotated}')"""
Out:['ab']
['abc', 'bc']
['abcd', 'bcd', 'cd']
[]
['ae']
[]
['fe']
Result: [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a@'), ('a', 'e'), ('e', 'a@'), ('f', 'e')]
"""
https://en.xdnf.cn/q/118956.html

Related Q&A

Pandas : How to drop #DIV/0! and NA values in new column in pandas dataframe?

I did some calculation and have #DIV/0! in my dataframe. How to drop these values and count further ? I followed df.dropna but dataframe still counting #DIV/0!. Please suggest.df.insert(loc=df.column…

unsupported operand for 3 instances of two classes and one method?

Im trying to get the program to take the hp stat from enemyUnit, the attack stat from unit, and the damage stat from tackle and put them into one math problem in the method getHit(). this is the code:…

Telling the script to wait until button is clickable? [duplicate]

This question already has answers here:Check whether element is clickable in selenium(3 answers)Closed 4 years ago.Im writing a script in Selenium (Python) and I am having an issue with a disabled clic…

Python: UnicodeDecodeError: utf8

Im having problem to save accented letters. Im using POSTGRESQL and Python 2.7POSTGRESQL - ENCODING = LATIN1I already added this line but does not worked! #!/usr/bin/python # -*- coding: UTF-8 -*-More…

Get continuous response of POST request in python

Im writing a script which does a POST request to a server and gets blocked the server keeps sending the response whenever a specific event is triggered. I have to take a cookie for post request with ea…

DataType of Pandas Multiindex [duplicate]

This question already has answers here:get the dtype of a pandas multiindex(3 answers)Closed 6 years ago.import pandas as pd index = pd.MultiIndex.from_tuples([(1,2, None), (1,2,3)]) print(index.get_le…

Is there a way to see the internal representation of float?

In python tutorial for floating point, In base 2, 1/10 is the infinitely repeating fraction0.0001100110011001100110011001100110011001100110011...How do I get python interpreter to print this intenal re…

Create function from try-except

Based on the example provided in this answer, how can I create a function from:from collections import Counter s = [0, 0, 2, 1, 1, 0, 0, 0] try:print(next(t[0] for t in Counter(s).most_common(2) if t[…

Bad request error flask with POST request

I have the following route that is getting values from a submitted form@app.route(/authenticate, methods=["POST"]) def authenticate():username = request.form[username]print(username, file = s…

How to use matplotlib/numpy to plot heatmap given three irregular lists of values in Python

Im wondering if there is a way to use matplotlib and numpy to plot the heatmap of three lists. My grid is not regular, it is oddly shaped so this does not work for me: Plotting a Heat Map X,Y,Intensity…