Professional Documents
Culture Documents
Implement Stack and Its Operations Using List and List Functions. Also Incorporate Minimum Two Exceptions While Implementing Stack
Implement Stack and Its Operations Using List and List Functions. Also Incorporate Minimum Two Exceptions While Implementing Stack
def push(stack,x):
try:
if int(x) in [0,1,2,3,4,5,6,7,8,9]:
print("Task cannot be an integer!")
return
except ValueError:
stack.append(x)
print("Item pushed successfully!")
def pop(stack):
try:
return stack.pop()
except IndexError:
print("Stack is empty!")
def isempty(stack):
if len(stack) == 0:
return True
else:
return False
def size(stack):
return len(stack)
def top(stack):
try:
return stack[0]
except IndexError:
print("Stack is empty!")
def disp(stack):
if not isempty(stack):
return stack
else:
print("Stack is empty!")
stack = [] #Stack contains a list of to-do tasks
option = 1
while option in [1,2,3,4,5,6]:
print("\n\n1.Enter a task(Push)\n2.Mark task as completed(Pop)\n3.Check if all tasks are
option = int(input())
if option == 1:
print("\nEnter task: ")
item = input()
push(stack,item)
elif option == 2:
print("\nPopped task: ",pop(stack))
elif option == 3:
e opt o 3:
if isempty(stack):
print("\nStack is empty!")
else:
print("\nStack is not empty")
elif option == 4:
print("\nThe no of tasks(size) is ",size(stack))
elif option == 5:
print("\nThe first task in the stack-",top(stack))
elif option == 6:
print("Tasks-\t",stack)
else:
print("\nInvalid option!")
1.Enter a task(Push)
1.Enter a task(Push)
1.Enter a task(Push)
Tasks- []
1.Enter a task(Push)
Stack is empty!
1.Enter a task(Push)
Invalid option!