Advertisement
Fhernd

protocolo-iterador.py

Jun 13th, 2018
1,688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. class Nodo:
  2.     def __init__(self, valor):
  3.         self.valor = valor
  4.         self._hijos = []
  5.  
  6.     def __repr__(self):
  7.         return 'Nodo({!r})'.format(self.valor)
  8.  
  9.     def agregar_hijo(self, nodo):
  10.         self._hijos.append(nodo)
  11.  
  12.     def __iter__(self):
  13.         return iter(self._hijos)
  14.  
  15.     def profundidad_primero(self):
  16.         yield self
  17.  
  18.         for c in self:
  19.             yield from c.profundidad_primero()
  20.  
  21. if __name__ == '__main__':
  22.     raiz = Nodo(0)
  23.     hijo1 = Nodo(1)
  24.     hijo2 = Nodo(2)
  25.  
  26.     raiz.agregar_hijo(hijo1)
  27.     raiz.agregar_hijo(hijo2)
  28.  
  29.     hijo1.agregar_hijo(Nodo(3))
  30.     hijo1.agregar_hijo(Nodo(4))
  31.     hijo2.agregar_hijo(Nodo(5))
  32.  
  33.     for hijo in raiz.profundidad_primero():
  34.         print(hijo)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement