-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstack-array-1.py
82 lines (62 loc) · 1.97 KB
/
stack-array-1.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of DSA course available on CourseGalaxy.com
class StackEmptyError(Exception):
pass
class StackFullError(Exception):
pass
class Stack:
def __init__(self,max_size=10):
self.items = [None] * max_size
self.count = 0
def size(self):
return self.count
def is_empty(self):
return self.count == 0
def is_full(self):
return self.count == len(self.items)
def push(self,x):
if self.is_full():
raise StackFullError("Stack is full, can't push")
self.items[self.count] = x
self.count+=1
def pop(self):
if self.is_empty():
raise StackEmptyError("Stack is empty, can't pop")
x = self.items[self.count-1]
self.items[self.count-1] = None
self.count-=1
return x
def peek(self):
if self.is_empty():
raise StackEmptyError("Stack is empty, can't peek")
return self.items[self.count-1]
def display(self):
print(self.items)
##########################################################
if __name__ == "__main__":
st = Stack(8)
while True:
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Size")
print("4.Display")
print("6.Quit")
choice = int(input("Enter your choice : "))
if choice == 1:
x=int(input("Enter the element to be pushed : "))
st.push(x)
elif choice == 2:
x=st.pop()
print("Popped element is : " , x)
elif choice == 3:
print("Element at the top is : " , st.peek())
elif choice == 4:
print("Size of stack " , st.size())
elif choice == 5:
st.display()
elif choice == 6:
break
else:
print("Wrong choice")
print()