basel117
basel117

Reputation: 189

tree nodes defined with a tree

I am working with trees in python and this is the problem I am trying to solve.

All my nodes have lists. For every parent, the children's lists are extracted from the parents list by removing one element at a time.

Let's say node1 is the list1 [1,2,3] I want to have 3 children (in this case) for node1 where every child is a list extracted from list 1 by removing one item at a time. and so node2=[2,3] node3=[1,3] and node4=[1,2]

I am working with anytree library but I can't find enough documentation on complex nodes. I currently have written this method but I am doubting the syntax:

  from anytree import Node, RenderTree
 #some othercode
    def createNodes(parentnode):
        for i in (0,K,1):
            childnode=Node(parentnode.pop(i), parent=parentnode)
            return childnode

does this code works as a solution? p.s: this is the tutorial I followed on Anytrees [https://anytree.readthedocs.io/en/2.6.0/intro.html#basics][1]

Upvotes: 0

Views: 77

Answers (1)

Anubhav Singh
Anubhav Singh

Reputation: 8699

Try this:

class Node:
    def __init__(self, data):
        self.data = data
        self.child = 3*[None]
        for i in range(len(data)):
            elem = data.pop(i)
            self.child[i] = data
            print(self.child[i])
            data.insert(i, elem)


data = [1, 2, 3]
root = Node(data)

output:

[2, 3]
[1, 3]
[1, 2]

Alternatively, you can try this:

class Node:
    def __init__(self, data, parent):
        self.parent = parent
        self.data = data

def createNodes(parentnode):
    data = parentnode.data
    for i in range(len(data)):
        elem = data.pop(i)
        childnode = Node(data, parent=parentnode)
        print(childnode.data)
        data.insert(i, elem)

root = Node([1, 2, 3], None)
createNodes(root)

output:

[2, 3]
[1, 3]
[1, 2]

Upvotes: 1

Related Questions