trees, iterations and adding leaves

V

vertigo

Hello

I have trees like this:
from nltk_lite.parse.tree import Tree
tree6 = Tree('main', ['sub1', 'sub2'])
tree6
('main': 'sub1' 'sub2')

I use nltk package - but it should not matter here.
I could change it's lafes (add node) like this:
tree6[0] = Tree('newsub',[])
tree6
('main': ('newsub': ) 'sub2')

But my tree has many levels and it's imposibble to address it like:
tree6[0][1][0][1][1][1][0]..........

So i wanted to 'travel thru my tree' to last node which should be changed:
tree6 = Tree('main', ['sub1', 'sub2'])
subtree = tree6[0]
subtree 'sub1'
subtree = Tree('newsub',[])
subtree ('newsub': )
tree6
('main': 'sub1' 'sub2')

The problem is that subtree is some kind of a new variable (not pointer)
so changing it i will not alter tree6. How to alter tree6 while
'travelling along it's nodes',
without messy referencing as tree6[0][1][0][1][1][1][0].......... ?

Thanx
 
G

Gabriel Genellina

I use nltk package - but it should not matter here.

Yes, it does. The framework should provide some form of tree traversal.
So i wanted to 'travel thru my tree' to last node which should be changed:
tree6 = Tree('main', ['sub1', 'sub2'])
subtree = tree6[0]
subtree 'sub1'
subtree = Tree('newsub',[])
subtree ('newsub': )
tree6
('main': 'sub1' 'sub2')
The problem is that subtree is some kind of a new variable (not pointer)
so changing it i will not alter tree6.

This, yes, is a general Python question. When you bind something to
the name "subtree", it doesn't matter what were "subtree" pointing to
before. Read http://effbot.org/zone/python-objects.htm
How to alter tree6 while
'travelling along it's nodes',
without messy referencing as tree6[0][1][0][1][1][1][0].......... ?

Without any further knowledge of the Tree objects, you could do
something like this:

def traverse_tree(tree, *ids):
result = tree
while ids:
key = ids.pop(0)
tree = tree[key]
return tree

and say: traverse_tree(tree6, 0, 1, 0, 1, 1, 1, 0) or
traverse_tree(tree6, *[0,1,0,1,1,1,0]) or traverse_tree(tree6,
*[0,1,0,1,1])[0] = another_object


--
Gabriel Genellina
Softlab SRL






__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top