0

I am working on a graph problem which is special in the sense that the nodes are computed only when required. This is because the graph is so huge that the entire graph won't fit in memory.

So, in my code I only have a node class and a computeChildren() method which gets called only when needed. I also have certain global parameters which are to be computed when the initNode is initialized. I am trying to figure out the best way to store these parameters. I thought about updating the parameters in the init method of the class but this causes the same computations to be repeated whenever a new node is computed.

I am using python3, could someone please suggest the right way to do this ...

UPD: The values used to initialize the init node decide the graph structure, this information is same for all nodes.

Some details regarding my coding background : I have mostly coded in C with some limited expertise in C++.

  • Use a boolean field to ensure the initialization occurs only once. Use fields that are specific to the class and not the instance (static attributes). – Frank Hileman Sep 27 '17 at 17:39
1

If it's global state, don't store it in the node class. Store it in the object which represents the whole graph, and reference the single instance of that object in your node objects.

  • Currently, I do not have an object representing the graph. I can definitely create one but I will still have to wait for the init node to be initialized before I can compute the parameters ... So, the same question remains, how do I prevent the computation from repeating for the other nodes. – vorzawk Sep 27 '17 at 17:15
  • Set a flag to say you've computed the global state. Be careful with threading issues. – Philip Kendall Sep 27 '17 at 18:09
  • @jachawk You mean that the paremeters must be computed right after the first node is initialized? Not before? Not in the middle? You should edit your question to clarify this. – Goyo Sep 27 '17 at 18:55
0

The suggestion of adding a class representing the whole graph makes sense. Instances of this class can take care of computing the parameters when and only when they should be computed. It also avoids the need for global state, which is a problem by itself.

class Graph:
    def __init__(self):
        self.first_node = Node()
        self.parameters = compute_parameters()

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.