Start free

Advanced · Stacks and queues · 206 of 264

Back and forward

Simulate a browser starting at home: visit <page> opens a page (and clears the forward history), back and forward move through the history when possible. Print the current page after every command.

Input: n, then n commands. Output: n lines.

Examples

Input
6
visit a
visit b
back
back
forward
visit c
Output
a
b
a
home
a
c
Input
2
back
forward
Output
home
home

One more test checks other inputs when you press Check.

Stuck? The idea behind stacks and queues

A stack is last in, first out: a list's append() and pop(). A queue is first in, first out: collections.deque with append() and popleft().

Stacks match brackets and undo actions; queues serve things in the order they came.

stack = []
for ch in "(()":
    if ch == "(":
        stack.append(ch)
    elif stack:
        stack.pop()
print("left open:", len(stack))

Watch for: pop() on an empty list stops the program: check the stack isn't empty first.

All the stacks and queues exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More stacks and queues exercises