Created
February 21, 2018 02:50
-
-
Save rafiamafia/babcf59457cfabdd0f8c7b5de45f1864 to your computer and use it in GitHub Desktop.
Stack implementation in 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
class PyStack(): | |
def __init__(self): | |
self._items = [] | |
def push(self, item): | |
self._items.append(item) | |
def pop(self): | |
if not self.isEmpty(): | |
return self._items.pop() | |
else: | |
return IndexError('Invalid pop: stack is empty.') | |
def isEmpty(self): | |
return True if len(self._items) == 0 else False | |
def peek(self): | |
if not self.isEmpty(): | |
return self._items[-1] | |
else: | |
return IndexError('Invalid peek: stack is empty.') | |
def __repr__(self): | |
return "[{}]".format(", ".join(map(str, self._items))) | |
def __iter__(self): | |
for i in self._items: | |
yield i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment