15.12.2022 Views

Python Eficaz

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

bar.__getitem__(0)

Para fazer a classe BinaryNode atuar como uma sequência, basta providenciar

uma implementação de __getitem__ que navegue primeiro pela maior dimensão

da árvore do objeto.

class IndexableNode(BinaryNode):

def _search(self, count, index):

# ...

# Retorna (found, count)

def __getitem__(self, index):

found, _ = self._search(0, index)

if not found:

raise IndexError('Index out of range')

return found.value

Depois, basta construir a árvore binária normalmente.

tree = IndexableNode(

10,

left=IndexableNode(

5,

left=IndexableNode(2),

right=IndexableNode(

6, right=IndexableNode(7))),

right=IndexableNode(

15, left=IndexableNode(11)))

Além do formato de árvore binária, também é possível acessá-la como uma list.

print('LRR =', tree.left.right.right.value)

print('Index 0 =', tree[0])

print('Index 1 =', tree[1])

print('11 in the tree?', 11 in tree)

print('17 in the tree?', 17 in tree)

print('Tree is', list(tree))

>>>

www.full-ebook.com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!