Theory of Intelligence
11TH•Computer Science•Computational Structures•Question 2

Solution

Explain the operations on stack with real-life example and Python code.

Solution

A stack adds and removes items only at the top, following LIFO (Last-In, First-Out). The two basic operations are push (add to the top) and pop (remove from the top).

Real-life example: A stack of books. You place Book A, then Book B on top. When you take a book, you take Book B first—the last one added.

PYTHON
# Create an empty stack of books
stack_of_books = []
print("Initial stack:", stack_of_books)  # Empty stack

# Add books to the stack (push operation)
print("\n Adding books to the stack (push operation):")
stack_of_books.append('Book A')
print("Stack after pushing 'Book A':", stack_of_books)
stack_of_books.append('Book B')
print("Stack after pushing 'Book B':", stack_of_books)

# Remove the top book from the stack (pop operation)
print("\nDeletion of top book (pop operation):")
top_book = stack_of_books.pop()
print("Removed book:", top_book)
print("Stack after popping the top book:", stack_of_books)

The code creates an empty stack, pushes "Book A" and "Book B", then pops the top book "Book B", showing that the last book added is the first one taken off.

Discuss theoretical concepts, mathematical formulas, and architectural foundations.

Supports inline code with `backticks`
No comments yet. Be the first to start the discussion!