Skip to content

Instantly share code, notes, and snippets.

@rafiamafia
Created February 21, 2018 02:50
Show Gist options
  • Save rafiamafia/babcf59457cfabdd0f8c7b5de45f1864 to your computer and use it in GitHub Desktop.
Save rafiamafia/babcf59457cfabdd0f8c7b5de45f1864 to your computer and use it in GitHub Desktop.
Stack implementation in Python
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