开发者

Non Sequential Loop Optimization in Python

开发者 https://www.devze.com 2023-04-10 14:32 出处:网络
I have two dictionary objects, connections and network. This can be visualized as a graph, where each node is a computer and connections depict an edge between the computers and node. Network is a dic

I have two dictionary objects, connections and network. This can be visualized as a graph, where each node is a computer and connections depict an edge between the computers and node. Network is a dictionary objects of unique networks where the computers can be a part, for ex

1,2  
2,3  
4,5  
5,1 

are four connection information for nodes 1 through 1

connections would thus be {1->1,2->1,3->1,4->2,5->1}

and network {1->0,2->1}

which means

computer 1,2,3,5 are part of n/w 1

computer 4 is part of n/w 2

again n/w 2 is interconnected to n/w 1

I have to read a file with thousand of such 开发者_运维知识库connection information

while doing so, for each connection info read I have to perform a non-sequential loop as follows

while network.has_key(connections[node1]):
    connections[node1]=network[connections[node1]] 

Is there a better way to optimize the above loop? If required I can share my entire code for the purpose


I'm didn't really understand your question, but I feel the stock answer to graph-related questions applies here:

Use NetworkX rather than trying to come up with your own data representations and algorithms. It may be harder to learn, but it'll save you time and headaches in the long run.


while network.has_key(connections[node1]):
    connections[node1]=network[connections[node1]] 

That code does the lookup for network[connections[node1]] twice once for has_key and once for [].

It also repeatedly accesses connections[node1]

Instead you can do:

current = connections[node1]
while True:
    try:
         current = network[current]
    except KeyError:
         break
connections[node1] = current

But chances are better improvements can be had be reworking the rest of your code. But for that you may find http://codereview.stackexchange.com to be a better site.

0

精彩评论

暂无评论...
验证码 换一张
取 消