- Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathP34_Stack.py
More file actions
Latest commit
58 lines (48 loc) · 1.68 KB
/
Copy pathP34_Stack.py
File metadata and controls
58 lines (48 loc) · 1.68 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
#Author: OMKAR PATHAK
#This program illustrates an example of Stack implementation
#Stack Operations: push(), pop(), isEmpty(), peek(), stackSize()
classStack(object):
def__init__(self, size):
self.index= []
self.size=size
def__str__(self):
myString=' '.join(str(i) foriinself.index)
returnmyString
defpush(self, data):
''' Pushes a element to top of the stack '''
if(self.isFull() !=True):
self.index.append(data)
else:
print('Stack overflow')
defpop(self):
''' Pops the top element '''
if(self.isEmpty() !=True):
returnself.index.pop()
else:
print('Stack is already empty!')
defisEmpty(self):
''' Checks whether the stack is empty '''
returnlen(self.index) == []
defisFull(self):
''' Checks whether the stack if full '''
returnlen(self.index) ==self.size
defpeek(self):
''' Returns the top element of the stack '''
if(self.isEmpty() !=True):
returnself.index[-1]
else:
print('Stack is already empty!')
defstackSize(self):
''' Returns the current stack size '''
returnlen(self.index)
if__name__=='__main__':
myStack=Stack(10)
foriinrange(0, 10):
myStack.push(i)
print(myStack.isEmpty()) # False
print(myStack.isFull()) # True
print(myStack) # 0 1 2 3 4 5 6 7 8 9
print(myStack.stackSize()) # 10
print(myStack.pop()) # 9
print(myStack) # 0 1 2 3 4 5 6 7 8
print(myStack.peek()) # 8