A turnstile is a classic finite state machine with two states, locked and unlocked, and two inputs, coin and push.
What to build
Run the turnstile on a list of events and print its state after each event.
Requirements
- The machine starts
locked. coinalways leads tounlocked, whatever the state was.pushalways leads tolocked: a person walks through, or pushes against a locked arm.
Input
The first line has the number of events e. Then e lines, each coin or push.
Output
e lines: the state after each event.
Constraints
1 ≤ e ≤ 20.
Example
Input:
4
coin
push
push
coin
Output:
unlocked
locked
locked
unlocked
Why it works
A state machine has a state and a table of what the next state is for each input. Here the table has four entries, and the next state depends only on the event, so the code is a lookup. The machine remembers only its state, not the history, which is the idea of a finite state machine.
Examples
4 coin push push coin
unlocked locked locked unlocked
2 coin coin
unlocked unlocked
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the state as a string, starting with `locked`.
Hint 2
A coin always makes the state `unlocked`. A push makes the state `locked`.
Hint 3
Print the state after every event, one per line.
Solution
Show one correct solution (try it yourself first)
e = int(input())
state = "locked"
table = {("locked", "coin"): "unlocked", ("unlocked", "coin"): "unlocked", ("locked", "push"): "locked", ("unlocked", "push"): "locked"}
for _ in range(e):
event = input().strip()
state = table[(state, event)]
print(state)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step