Pending queue
- Algorithms course
- Intermediate
- Lesson 47/80
- 4 min
Keep pending tasks in a queue.
Pending queue
Now we write the undo operation. pop_undo removes and returns the last action from the stack; this performs the undo.
If the stack is empty there is nothing to undo. In that case a user-friendly message is returned and an error is avoided.
The pop operation: stack.pop(). It removes and returns the last element. Thanks to LIFO the most recent action is undone.
Empty stack check
Before popping we must check whether the stack is empty. Pop on an empty stack raises an error and may crash the program.
In Python if not stack: checks for an empty list. If empty return a message, otherwise pop. This provides a safe undo.
This check is essential for a user-friendly and error-free undo system; it must always be done.
Practice Undo
Write pop_undo(stack). 'boş' if empty, else pop. Print ekle with s = init_undo(); push_undo(s, 'ekle'); print(pop_undo(s)).
Starter code
def init_undo():
# Empty undo stack
return []
def push_undo(stack, action):
# Push to undo stack
stack.append(action)
return stack
def pop_undo(stack):
# Pop from undo stackSample solution
def init_undo():
# Empty undo stack
return []
def push_undo(stack, action):
# Push to undo stack
stack.append(action)
return stack
def pop_undo(stack):
# Pop from undo stack
if not stack:
return 'boş'
return stack.pop()
s = init_undo()
push_undo(s, 'add')
print(pop_undo(s))Expected output
ekle
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pending queue: match the terms
| Term | Meaning |
|---|---|
Pop |
Remove |
Empty stack |
Message |
LIFO |
Last first |
Undo |
Reverse |
2 What should pop do on an empty stack?
- Raise error
- Take the last
- Crash
- Return a message Correct answer
Explanation: Return a message
3 Pop operation
return stack.____()
return stack.pop()
Explanation: pop is right.