By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,270 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,270 IT Pros & Developers. It's quick & easy.

trees, iterations and adding leaves

P: n/a
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
Dec 31 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
At Sunday 31/12/2006 14:25, vertigo wrote:
>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

Jan 2 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.