Introduction
Imagine you have a stack of plates. You can only add a new plate on top or take the top plate off. This problem of managing items in a last-in, first-out order is solved by stack operations.
Think of a stack of books on a table. You add a new book on top (push), take the top book off to read (pop), or just look at the title of the top book without moving it (peek).
Stack (top) ┌─────┐ │ 3 │ <-- Peek shows this ├─────┤ │ 2 │ ├─────┤ │ 1 │ └─────┘ Operations: Push: Add new item on top Pop: Remove top item Peek: View top item
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.items: return None return self.items.pop() def peek(self): if not self.items: return None return self.items[-1] stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.peek()) # Should print 3 print(stack.pop()) # Should print 3 print(stack.peek()) # Should print 2
pop operation do in a stack?5 to a stack named s using the push operation?push(item).s.push(5) correctly adds 5 to the stack.s.push(10)
s.push(20)
s.pop()
s.push(30)
top = s.peek()
top after these operations?push(10), stack = [10]. After push(20), stack = [10, 20]. After pop(), top 20 is removed, stack = [10]. After push(30), stack = [10, 30].top = 30.stack = [] stack.push(1) stack.push(2) item = stack.pop()
append() to add items, not push(). Using push() causes an error.[1, 2, 3] using a stack. Which sequence of stack operations correctly reverses the list?Pass the test and this pattern moves unknown