Solution For Practical Exam
Solution For Practical Exam
def factorial(n):
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
Question 3 stack
def is_full(stk):
if len(stk) == 5:
return False
else:
return True
def is_Empty(stk):
if stk == [ ]:
return True
else:
return False
def pop(stk):
if is_Empty (stk) :
return "Underflow"
else:
item = stk.pop()
if len(stk) == 0:
top = None
else:
top = len(stk)-1
return item
def peek(stk) :
if is_Empty(stk) :
return "Underflow"
else:
top = len(stk) -1
return stk[top]
def Display(stk) :
if is_Empty(stk) :
print(":stack empty")
else:
top = len(stk) -1
print(stk[top], "<- top" )
for a in range(top- 1, -1, -1 ) :
print(stk [a])
#_main_
stack = [ ] # initially stack is empty
top = None
while True:
print("STACK OPERATIONS")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display stack")
print("5. Exit")
ch = int(input("Enter your choice (1-5) :"))
if ch == 1 :
item = int(input("Enter item:"))
status=push (stack, item)
if status =="Overflow":
print("Stack is full, Cannot Push")
else:
print(item, " pushed in stack")
elif ch == 2 :
item = pop(stack)
if item =="Underflow":
print("underflow : stack is empty !")
else:
print("popped item is", item)
elif ch == 3:
item = peek(stack)
if item =="Underflow":
print("underflow! Stack is empty!")
else:
print("Topmost item is", item)
elif ch == 4:
Display(stack)
elif ch == 5:
break
else:
print("Invalid choice!")