VisioN
VisioN

Reputation: 145478

Function of walking down the tree structure with setting paths

I've spent couple of hours and still unable to get the best result. However, the task is very easy but it seems I'm missing something or simply slow today.

So, we have a simple tree structure of objects. Object in formal looks like this:

node:
    name {str}
    value {str}
    children {list}
        node,
        node,
        ...

I need to create the walk function that outputs the list of all nodes in the format of list of tuples:

for node in topNode.walk():
    path, object = node

where path is obviously a path to the current node (i.e. /name/name). Almost the same does os.walk() function.

At the moment I'm in stuck with this piece of code:

def walk(self):
    result = []
    for child in self.children:
        result.append(child)
        result.extend(child.walk())
    return result

How to add path in here?

Thanks for any help!

Upvotes: 0

Views: 579

Answers (2)

mgilson
mgilson

Reputation: 310257

This might work -- I cooked it up in my head and haven't tested it...

 def walk(self,_root='/'):
     result=[]
     for child in self.children:
         path="%s%s/"%(_root,child.name) if child.children else "%s%s"%(_root,child.name)
         result.append((path,child))
         result.extend(child.walk(_root=path))

     return result  #result if _root != '/' else zip(*result)

EDIT

Fixed the return statement to match your edit above.

Upvotes: 1

ubik
ubik

Reputation: 4560

Do whatever you have to do with child in order to get the composite path, and then pass on child.name as a parameter of walk (it can even be a keyword argument).

Something like...

def walk(self, path=''):
    result = []
    for child in self.children:
        child_path = path + '/' + child.name
        result.append((child_path, child))
        result.extend(child.walk(child_path))
    return result

Upvotes: 3

Related Questions