Skip to content
Advertisement

Optimizing python script to produce output faster (Variable Assignment)

I am using python for optimization purposes. I made a graph using Networkx library with 1100 nodes. The python script includes the following lines.

JavaScript

In the next step, some random numbers are generated as follows:

JavaScript

I compute the distance between nodes in the graph using the following function.

JavaScript

Finally, I defined the variable “shipping_cost” as:

JavaScript

Every line of the above code is executed in short manner (milliseconds). But, the assignment the value to the variable “shipping_cost” is not completed even after 7 hours. The variable logically contains 1210000 values.

  1. Does it seem normal in terms of running time?
  2. Is there any way to decrease the execution time of shipping_cost assignment?

Advertisement

Answer

Based on the comments by @Ram:

The cartesian_prod contains 1210000 values. The code is calling compute_distance() which in turn calls shortest_path() and path_length()for all the 1210000 values from networkx library. That’s the reason calculating shipping_cost takes lot of time to compute.

I changed the code as follows (path_lengths is added instead of compute_distance and shipping_cost is modified):

JavaScript

By doing so, the path_lengths is calculated once for all nodes, and the time complexity is focused on accessing the elements of path_lengths.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement