-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstack_menu.py
More file actions
71 lines (55 loc) · 1.47 KB
/
Copy pathstack_menu.py
File metadata and controls
71 lines (55 loc) · 1.47 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
70
71
class StackFullError(Exception):
def __init__(self):
self.message = "Stack is full"
class StackEmptyError(Exception):
def __init__(self):
self.message = "Stack is empty"
class Stack:
def __init__(self, limit=10):
self.data = []
self.limit = limit
def push(self, value):
if len(self.data) == self.limit:
raise StackFullError()
self.data.append(value)
def pop(self):
if len(self.data) == 0:
raise StackEmptyError()
return self.data.pop()
def peek(self):
if len(self.data) == 0:
return None
return self.data[-1]
@property
def length(self):
return len(self.data)
s = Stack(5)
while (True):
print("\nMenu")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Length")
print("5. Exit")
choice = int(input("Enter choice : "))
if choice == 1:
value = input("Enter a value :")
try:
s.push(value)
except StackFullError:
print("Sorry! Stack is already full!")
elif choice == 2:
try:
print("Value = ", s.pop())
except StackEmptyError:
print("Sorry! Stack is empty!")
elif choice == 3:
value = s.peek()
if value is None:
print("Sorry! Stack is empty!")
else:
print("Value = ", value)
elif choice == 4:
print("Length = ", s.length)
else:
break