forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
Latest commit
69 lines (53 loc) · 1.92 KB
/
Copy pathstack.py
File metadata and controls
69 lines (53 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from __future__ importprint_function
__author__='Omkar Pathak'
classStack(object):
""" 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, First Out (LIFO).
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
"""
def__init__(self, limit=10):
self.stack= []
self.limit=limit
def__bool__(self):
returnbool(self.stack)
def__str__(self):
returnstr(self.stack)
defpush(self, data):
""" Push an element to the top of the stack."""
iflen(self.stack) >=self.limit:
raiseStackOverflowError
self.stack.append(data)
defpop(self):
""" Pop an element off of the top of the stack."""
ifself.stack:
returnself.stack.pop()
else:
raiseIndexError('pop from an empty stack')
defpeek(self):
""" Peek at the top-most element of the stack."""
ifself.stack:
returnself.stack[-1]
defis_empty(self):
""" Check if a stack is empty."""
returnnotbool(self.stack)
defsize(self):
""" Return the size of the stack."""
returnlen(self.stack)
classStackOverflowError(BaseException):
pass
if__name__=='__main__':
stack=Stack()
foriinrange(10):
stack.push(i)
print('Stack demonstration:\n')
print('Initial stack: '+str(stack))
print('pop(): '+str(stack.pop()))
print('After pop(), the stack is now: '+str(stack))
print('peek(): '+str(stack.peek()))
stack.push(100)
print('After push(100), the stack is now: '+str(stack))
print('is_empty(): '+str(stack.is_empty()))
print('size(): '+str(stack.size()))