loading…
CBSE Class 12 · Computer Science (083)
CBSE Class 12 Computer Science stack in Python: push, pop, peek and display programs with real output, board-style output questions and viva answers.
stack = []
def push(item):
stack.append(item)
def pop():
if not stack:
return "Underflow"
return stack.pop()
def peek():
return stack[-1] if stack else "Stack empty"
def display():
print(stack[::-1] if stack else "Stack empty")
while True:
ch = input("1.Push 2.Pop 3.Peek 4.Display 5.Exit: ")
if ch == "1":
push(int(input("Value: ")))
elif ch == "2":
print("Popped:", pop())
elif ch == "3":
print("Top:", peek())
elif ch == "4":
display()
else:
break
Output (typed input shown after each prompt)
1.Push 2.Pop 3.Peek 4.Display 5.Exit: 1 Value: 10 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 1 Value: 20 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 1 Value: 30 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 4 [30, 20, 10] 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 2 Popped: 30 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 3 Top: 20 1.Push 2.Pop 3.Peek 4.Display 5.Exit: 5
def push_div5(nums, stack):
for n in nums:
if n % 5 == 0:
stack.append(n)
def pop_all(stack):
while stack:
print(stack.pop(), end=" ")
print("\nStack empty")
S = []
push_div5([12, 15, 7, 40, 25, 3], S)
pop_all(S)
Output
25 40 15 Stack empty
stack = []
for ch in "BOARD":
stack.append(ch)
stack.pop()
stack.pop()
stack.append("X")
print(stack, stack[-1])
['B', 'O', 'A', 'X'] X
Why: A stack is Last In, First Out: pop() removes the most recent item.
def reverse(text):
st = []
for ch in text:
st.append(ch)
out = ""
while st:
out += st.pop()
return out
print(reverse("CBSE"), reverse(""))
ESBC
Why: Pushing every character then popping them all reverses the string.
PyRun is not affiliated with CBSE. Questions are written in the board's style for practice; they are not past papers.