Last active
January 2, 2018 18:16
-
-
Save dunossauro/55f319bd43abf3e575814c181223a3c9 to your computer and use it in GitHub Desktop.
Implementação simples de uma pilha em python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Auxilio a pergunta feita no facebook. | |
https://www.facebook.com/groups/python.brasil/permalink/1289629901141877/ | |
""" | |
class Stack(object): | |
def __init__(self): | |
"""Inicializa a pilha vazia.""" | |
self.p = [] # Aqui P vai ser a lista interna | |
def pop(self): | |
return self.p.pop() | |
def push(self, value): | |
self.p.append(value) | |
def __repr__(self): | |
"""Método para visualizar seu objeto.""" | |
return 'Stack({})'.format(self.p) | |
def __iter__(self): | |
"""Método que inicia o objeto a ser iterado.""" | |
return self | |
def __next__(self): | |
""" | |
Método que faz a iteração de fato, eliminando elemento a elemento. | |
""" | |
if not self.p: | |
raise StopIteration | |
return self.p.pop() | |
def __getitem__(self, value): | |
"""Alternativa não destrutiva a iteração. | |
Os valores serão mantidos mesmo depois de iterados. | |
Use __iter__ e __next__ ou somente __getitem__ | |
NOTE: Dessa maneira a iteração será iniciada usando a posição 0 | |
Você pode inverter a lista usando reversed(self.p) | |
""" | |
return self.p[value] | |
""" | |
Exemplo de uso. | |
In [1]: s = Stack() | |
In [2]: s.push(5) | |
In [3]: s | |
Out[3]: Stack([5]) | |
In [4]: s.push(10) | |
In [5]: s | |
Out[5]: Stack([5, 10]) | |
In [6]: for elemento in s: | |
...: print(elemento) | |
...: | |
10 | |
5 | |
In [7]: s | |
Out[7]: Stack([]) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment