Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate and delete specific edges in networkx directed graph

I have a graph with positive and negative edges in networkx. I want to find all the negative edges and reverse them. I wrote the program below to find and delete the negative edges but i get an iteration error. Here is the code:

for edge in G.edges():
    sign = G.get_edge_data(edge[0], edge[1])['sign']
    if sign == -1:
       G.remove_edge(edge[0], edge[1])
       G.add_edge(edge[1], edge[0])

How can i iterate through all edges and reverse all the negative edges?

like image 411
Lee Yaan Avatar asked Oct 16 '25 07:10

Lee Yaan


1 Answers

Changing elements of the iteration while iterating is evil ;o)

thingsToChange = []
for edge in G.edges():
    sign = G.get_edge_data(edge[0], edge[1])['sign']
    if sign == -1:
       thingsToChange.append(edge)

Changing them afterwards is fine:

for things in thingsToChange:
    G.remove_edge(edge[0], edge[1])
    G.add_edge(edge[1], edge[0])
like image 172
Patrick Artner Avatar answered Oct 17 '25 22:10

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!