0

I was experimenting with graphs in python and i felt into a problem.

Here is the code :

class IspNetwork :
    def __init__(self) -> None:
        self.root : Node = Node("isp")

    def add_node(self, obj) :
        node = ObjectEncoder().encode(obj)
        self.root.left = Node(node)
        pass

The output is as expected, one root node and a node on the left branch.

Now my question is, how to dynamically set multiple nodes on the left branch, it should be something like : self.left.left...left.left = Node(node)

But I cant figure out how to do it the right way.

I tried to use __setattr__(), some gibberish like self.left. + 3*"left" = Node(node).

But none of those worked so any help would be highly appreciated !

  • Can you fix the indentation of your code? How will you decide whether a node should go in the left subtree or in the right subtree? – trincot Mar 18 '23 at 14:24
  • What is the expected result if you call `add_node` 7 times? Is there some expected tree shape? – trincot Mar 18 '23 at 14:31
  • Yes will fix the indentation. The logic is not implemented yet, i was messing around trying to figure out how to manipulate the graph. If i call add_node multiple time it's only replace the value of the left branch. @trincot – kiraoverflow Mar 18 '23 at 14:44
  • Then I don't really see a question here. – trincot Mar 18 '23 at 14:45
  • My question is, setting the first node of the left branch is done by setting the attr "left" to a value but for setting the second level of the left branch it should be `self.left.left = value`. Is it possible to concatenate an object attribute name like `self.left + ".left" = value` or something like that ? – kiraoverflow Mar 18 '23 at 14:49
  • You would use a loop or recursion. But it all depends really on the logic by which you decide that a node should be placed at `self.right` or `self.left.right`, ...etc. – trincot Mar 18 '23 at 14:55
  • Thx for your help, i think i figured out ! :) I will edit my post ! – kiraoverflow Mar 18 '23 at 15:01
  • If you figured something out, make sure the question is clear (clarifying the points I asked about), and that your answer is not part of the question, but posted in the answer area. – trincot Mar 18 '23 at 15:05
  • 1
    Thank's you for the advice on formating a post, it was my first time here really apreciate it man ! – kiraoverflow Mar 18 '23 at 15:16

1 Answers1

0

To add a branch to a specific node we can set the index of the node we want to expand.

class IspNetwork :
    def __init__(self) -> None:
        self.root : Node = Node("isp")

    def add_node(self, index, obj) :
        self.root[index].__setattr__("left", Node(obj))

Thank's to @trincot for helping me solve the issue !