0
tuple = ('e', (('f', ('a', 'b')), ('c', 'd')))

how to get the positions: (binary tree)

[('e', '0'), ('f', '100'), ('a', '1010'), ('b', '1011' ), ('c', '110'), ('d', '111')]

is there any way to indexOf ?

arvore[0] # = e
arvore[1][0][0] # = f
arvore[1][0][1][0] # = a
arvore[1][0][1][1] # = b
arvore[1][1][0] # = c
arvore[1][1][1] # = d
1
  • 4
    Did you try anything? Provide us the code what you have tried. Commented Oct 11, 2014 at 13:51

1 Answer 1

5

You need to traverse the tuple recursively (like tree):

def traverse(t, trail=''):
    if isinstance(t, str):
        yield t, trail
        return
    for i, subtree in enumerate(t):  # left - 0, right - 1
        # yield from traverse(subtree, trail + str(i))   in Python 3.3+
        for x in traverse(subtree, trail + str(i)):
            yield x

Usage:

>>> t = ('e', (('f', ('a', 'b')), ('c', 'd')))
>>> list(traverse(t))
[('e', '0'), ('f', '100'), ('a', '1010'), ('b', '1011'), ('c', '110'), ('d', '111')]

BTW, don't use tuple as a variable name. It shadows builtin type/function tuple.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.