0

I have a key-word, e.g. friendly. It gives birth to a child-word, e.g. warm, while descending from a parent-word, e.g. 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.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63
wen
  • 1,875
  • 4
  • 26
  • 43
  • 1
    Maybe a `namedtuple` is not the right data structure for what you're trying to do, but it's a little unclear. Usually with questions like this it's best not to ask "How do I do _______ using specific tool _______?" and more "This is what I tried and here's why it didn't work; what could I do differently?" Because maybe you didn't choose the right tool in the first place. As it is the title of your question doesn't really mean anything useful. – Iguananaut Feb 21 '15 at 00:21
  • If you're trying to build a tree structure, for example, which it sounds like you are, there are plenty of materials out there already and representing trees in Python. – Iguananaut Feb 21 '15 at 00:22
  • How do I represent trees in Python? – wen Feb 21 '15 at 00:23
  • I think classes may be closer to what you want – Padraic Cunningham Feb 21 '15 at 00:26

1 Answers1

2

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.

Anthony Towns
  • 2,864
  • 1
  • 19
  • 23