1

I would like to build a tree structure that can be constructed easily, without having to remember the exact name of the branch. I know that this question has been discussed here, which solution works fine, but it still requires that the exact name of the key must be remembered. With the following solution I can use autocompletion:

class tree_dot:
""" A class to create a tree structure """

def __init__(self, name):
    self.name = name
    self.branches = []

def add_branch(self,branch_name):
    """ A method to add a branch to the tree which is itself a tree object """
    a = tree_dot(branch_name)
    setattr(self, branch_name, a)
    self.branches.append(a)

The output looking like this:

>>> Tree = tree_dot('Tree')
>>> Tree.add_branch('First')
>>> Tree.First.add_branch('Second')
>>> Tree.First.Second.add_branch('Third')
>>> Tree.First.Second.Third.name = 'This is the third branch !'

However, I feel uncomfortable with such a long name.name.name.name. Does that pose a problem? Is there a better way to do it?

Community
  • 1
  • 1
Sami
  • 11
  • 2

1 Answers1

0

Since it is recursive, to a certain extent it is impossible to avoid so many dots. In terms of using classes to represent recursive results, it is normal.

If you want to avoid remembering key names, you could always add a default attribute that is a list of connections:

Tree.c[0].c[0].c[1]

, or whatever indexes exist.

An alternate way to do it would be to have a keys/value system. Something that I sometimes do is:

(['first','second','third'], tree_dot())

which is a good way to remember keys. Especially if you are needing an application like network problems (e.g. Travelling Salesman), this can be useful, as it can be stored in a flat array (making comparisons and other functions easier) without losing data.

bcdan
  • 1,438
  • 1
  • 12
  • 25
  • Thanks for your answer. It seems useful but it misses the autocompletion feature that I find convenient, sort of a simple GUI. Also I don't get your :(['first','second','third'], tree_dot()), doesn't seem to work for me! – Sami Jul 24 '15 at 07:46