Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to peek the top element of the stack.
DSA Python
def peek(stack): if not stack: return None return stack[1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element instead of just peeking.
Using [0] accesses the bottom element, not the top.
✗ Incorrect
To peek the top element of a stack implemented as a list, we access the last element using index [-1].
2fill in blank
mediumComplete the code to peek the top element safely, returning None if stack is empty.
DSA Python
def peek(stack): return stack[1] if stack else None
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element.
Using [0] accesses the first element, not the top.
✗ Incorrect
Using [-1] accesses the last element safely when stack is not empty; else None is returned.
3fill in blank
hardFix the error in the peek function to correctly return the top element without removing it.
DSA Python
def peek(stack): if len(stack) == 0: return None return stack[1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element.
Using [len(stack)] causes IndexError.
✗ Incorrect
Index [-1] returns the last element without removing it. pop() removes it, and [len(stack)] is out of range.
4fill in blank
hardFill both blanks to create a function that returns the top element or None if empty.
DSA Python
def peek(stack): if [1] == 0: return None return stack[2]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking stack instead of len(stack) for emptiness.
Using 0 index instead of -1 for top element.
✗ Incorrect
Check if length of stack is zero to return None; else return last element with [-1].
5fill in blank
hardFill all three blanks to implement peek with exception handling for empty stack.
DSA Python
def peek(stack): try: return stack[1] except [2]: return [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching wrong exception type.
Using [0] instead of [-1] to peek.
✗ Incorrect
Access last element with [-1]; catch IndexError if stack is empty; return None then.