Search code examples
pythonrecursionmptt

python - mptt for nested lists


I have read a little about mptt solution and I'm trying to implement some sort of translating a nested list into a mptt list. I know, that in this format it's useless, but nested lists can be easily changed with a classes childs or anything else.

The code I have is:

tree = [[1,[[11,[111, 112, 113]],[12,]]],[2,[[21,[[211,[2111,]],]],]]]

class node():
    def __init__(self, value, lft):
        self.value = value
        self.lft = lft

    def add_right(self, rgt):
        self.rgt = rgt

    def __str__(self):
        return "%s | %s | %s" %(self.value, self.lft, self.rgt)

def numerate(table, tree, counter):
    for item in tree:
        if type(item) == type(1):
            table.append(node(item, counter))
            index = len(table)
            counter += 1
        else:
            table.append(node(item[0], counter))
            index = len(table)
            counter += 1

            if len(item) > 1:
                (table, counter) = numerate(table, item[1], counter)

        table[index-1].add_right(counter)
    return (table, counter)

table = numerate([], tree, 0)[0]

for item in table:
    print item

But the result is:

1 | 0 | 6
11 | 1 | 5
111 | 2 | 3
112 | 3 | 4
113 | 4 | 5
12 | 5 | 6
2 | 6 | 10
21 | 7 | 10
211 | 8 | 10
2111 | 9 | 10

I see there is something not ok with the right value in recursion. I think such a format in python might be sometimes useful, so it would be nice to have some code for it already written.


Solution

  • The problem has been solved by adding a global iterator.

    If someone is interested, that's the new numerate function, which actually works fine.

    global_iterator = 0
    
    def numerate(table, tree):
        global global_iterator
        for item in tree:
            global_iterator += 1
    
    
            if type(item) == type(1):
                table.append(node(item, global_iterator))
                index = len(table)
            else:
                table.append(node(item[0], global_iterator))
                index = len(table)
    
                if len(item) > 1:
                    table.append(numerate(table, item[1]))
    
            global_iterator += 1
    
            table[index-1].add_right(global_iterator)
    
        return table
    
    table = numerate([], tree)
    

    The node() does not change.