简体   繁体   中英

How to implement a tree structure in Python using namedtuple

I have a key-word, eg friendly. It gives birth to a child-word, eg warm, while descending from a parent-word, eg friend.

from collections import namedtuple

keyword = 'friendly'
childword = 'warm'
parentword = 'friend'

connect=namedtuple(keyword,'children parents')
output = connect([childword],[parentword])  

As a result, I can use output.children to see what are the children of my nodeword. However, what I really want to do is to type

friendly.children # instead of output.children

to see the children of the key-word friendly. How can I do this? I am completely new to Python; I am not even sure if this is doable.

If you want to define a tree structure, you could use a namedtuple for that:

from collections import namedtuple

TreeNode = namedtuple('TreeNode', ['word', 'children'])

friend = TreeNode(word='friend', children=[])
friendly = TreeNode(word='friendly', children=[])
warm = TreeNode(word='warm', children=[])

friend.children.append(friendly)
friendly.children.append(warm)

print(friendly.children)

which comes up with:

[TreeNode(word='warm', children=[])]

That's a very C-like way of doing things though; you're probably better off having a single Graph or Tree data structure that stores the edge relationships, eg:

children = dict()
children['friend'] = ['friendly']
children['friendly'] = ['warm']

def parents(word):
    ps = []
    for k in children:
        if word in children[k]:
            ps.append(k)
    return ps

print(children['friendly'])
print(parents('friendly'))

which comes up with

['warm']
['friendly']

There's an article on Implementing Graphs in Python available that you might find useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM