Print the state
- Algorithms course
- Intermediate
- Lesson 48/80
- 4 min
Print the contents of the stack and queue.
Print the state
In the last step we print the current state of the stack. This lets the user see the undo history and adds transparency.
To print the whole stack a loop or direct print(stack) is used. The contents are listed from bottom to top.
This is the final piece of the project; all functions work together to form a complete undo system.
State report
Printing the state lets the user see the undo history. The whole stack is listed; the first action at the bottom, the last at the top.
This shows the user what can be undone. It is also useful for debugging; it confirms the stack grows correctly.
In real text editors this is shown in a side panel.
Practice Print state
Write print_state(stack). Print the stack contents. Print ['ekle', 'sil'] with s = init_undo(); push_undo(s, 'ekle'); push_undo(s, 'sil'); print_state(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 stack
if not stack:
return 'boş'
return stack.pop()
def print_state(stack):
# Print stateSample 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()
def print_state(stack):
# Print state
print(stack)
s = init_undo()
push_undo(s, 'add')
push_undo(s, 'del')
print_state(s)Expected output
['ekle', 'sil']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Print the state: match the terms
| Term | Meaning |
|---|---|
init_undo |
Empty stack |
push_undo |
Push |
pop_undo |
Undo |
print_state |
2 What is done to see the stack state?
- print(stack) Correct answer
- append(stack)
- sort(stack)
- pop(stack)
Explanation: print(stack)
3 Printing
print(____)
print(stack)
Explanation: stack is right.