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 !

9
  • 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? Commented Mar 18, 2023 at 14:24
  • What is the expected result if you call add_node 7 times? Is there some expected tree shape? Commented Mar 18, 2023 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 Commented Mar 18, 2023 at 14:44
  • Then I don't really see a question here. Commented Mar 18, 2023 at 14:45
  • 1
    Thank's you for the advice on formating a post, it was my first time here really apreciate it man ! Commented Mar 18, 2023 at 15:16

1 Answer 1

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 !

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.