Last active
November 6, 2019 17:05
-
-
Save Citymonstret/c7284fe24b0db42219b711da936b8a3e to your computer and use it in GitHub Desktop.
Stack implementation in python
This file contains hidden or 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 Stack(object): | |
| """Initialize a new stack | |
| :param size the fixed stack size | |
| """ | |
| def __init__(self, size: int): | |
| self.__size = size | |
| self.__array = [None] * size | |
| self.__cursor = 0 | |
| """Push a value to the stack | |
| :param value The value to push | |
| :raises IndexError if the stack cursor exceeds | |
| the stack size | |
| """ | |
| def push(self, value): | |
| if self.__cursor >= self.__size: | |
| raise IndexError | |
| self.__array[self.__cursor] = value | |
| self.__cursor += 1 | |
| """Pop a value from the stack | |
| :return The popped object | |
| :raises IndexError if the stack cursor | |
| goes below 0 | |
| """ | |
| def pop(self) -> object: | |
| if self.__cursor <= 0: | |
| raise IndexError | |
| self.__cursor -= 1 | |
| temp = self.__array[self.__cursor] | |
| self.__array[self.__cursor] = None | |
| return temp | |
| """Peek the current value in the stack | |
| without decreasing the cursor | |
| """ | |
| def peek(self) -> object: | |
| if self.__cursor <= 0: | |
| raise IndexError | |
| return self.__array[self.__cursor - 1] | |
| def __len__(self) -> int: | |
| return self.__size | |
| """Check whether the stack has any remaining values | |
| to pop, or not | |
| :return True if the stack has values to pop | |
| """ | |
| def has_value(self) -> bool: | |
| return self.__cursor > 0 | |
| """Check whether the stack has any remaining capacity | |
| for push, or not | |
| :return True if the stack has remaining capacity | |
| """ | |
| def has_capacity(self) -> bool: | |
| return self.__cursor < self.__size | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment