A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In
| 3 | |
| 4 | |
| 5 | class Stack(object): |
| 6 | """ A stack is an abstract data type that serves as a collection of |
| 7 | elements with two principal operations: push() and pop(). push() adds an |
| 8 | element to the top of the stack, and pop() removes an element from the top |
| 9 | of a stack. The order in which elements come off of a stack are |
| 10 | Last In, First Out (LIFO). |
| 11 | |
| 12 | https://en.wikipedia.org/wiki/Stack_(abstract_data_type) |
| 13 | """ |
| 14 | |
| 15 | def __init__(self, limit=10): |
| 16 | self.stack = [] |
| 17 | self.limit = limit |
| 18 | |
| 19 | def __bool__(self): |
| 20 | return bool(self.stack) |
| 21 | |
| 22 | def __str__(self): |
| 23 | return str(self.stack) |
| 24 | |
| 25 | def push(self, data): |
| 26 | """ Push an element to the top of the stack.""" |
| 27 | if len(self.stack) >= self.limit: |
| 28 | raise StackOverflowError |
| 29 | self.stack.append(data) |
| 30 | |
| 31 | def pop(self): |
| 32 | """ Pop an element off of the top of the stack.""" |
| 33 | if self.stack: |
| 34 | return self.stack.pop() |
| 35 | else: |
| 36 | raise IndexError('pop from an empty stack') |
| 37 | |
| 38 | def peek(self): |
| 39 | """ Peek at the top-most element of the stack.""" |
| 40 | if self.stack: |
| 41 | return self.stack[-1] |
| 42 | |
| 43 | def is_empty(self): |
| 44 | """ Check if a stack is empty.""" |
| 45 | return not bool(self.stack) |
| 46 | |
| 47 | def size(self): |
| 48 | """ Return the size of the stack.""" |
| 49 | return len(self.stack) |
| 50 | |
| 51 | |
| 52 | class StackOverflowError(BaseException): |
no outgoing calls
no test coverage detected