Python / 2.py
Madhan-Alagarsamy's picture
Upload 2.py
480765c verified
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
print("The element", e, "is pushed successfully")
def top(self):
if self.is_empty():
raise Empty("Stack is Empty!")
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty("Stack is Empty!")
return self._data.pop()
print("\t Stack ADT Implementation")
print("\t---------------------------------")
stack = ArrayStack()
while True:
print("\n\t Stack Operations:")
print("1 - Push")
print("2 - Pop")
print("3 - Top element")
print("4 - Length of stack")
print("5 - Is empty")
print("6 - Display stack elements")
print("7 - Exit")
ch = int(input("Enter your choice: "))
try:
if ch == 1:
e = int(input("Enter the element: "))
stack.push(e)
elif ch == 2:
t = stack.pop()
print("The element", t, "is popped successfully")
elif ch == 3:
t = stack.top()
print("The top element in the stack is", t)
elif ch == 4:
print("Number of elements in stack is", len(stack))
elif ch == 5:
if stack.is_empty():
print("Stack is Empty")
else:
print("Stack is not empty")
elif ch == 6:
if stack.is_empty():
print("Stack is empty")
else:
print("Elements in stack (Top to Bottom):")
for i in range(len(stack) - 1, -1, -1):
print("|", stack._data[i], "|")
print("-------------")
elif ch == 7:
print("Program exited")
break
else:
print("Invalid choice")
except Empty as e:
print(e)
except ValueError:
print("Please enter a valid number")