Skip to content

Instantly share code, notes, and snippets.

@tribela
Last active February 12, 2026 14:56
Show Gist options
  • Select an option

  • Save tribela/16df907f8bf42885514f8f5eb02bf790 to your computer and use it in GitHub Desktop.

Select an option

Save tribela/16df907f8bf42885514f8f5eb02bf790 to your computer and use it in GitHub Desktop.
Hanoi tower, without recursion, Just state -> next state
import pytest
def step_parity(state: list[int]) -> bool:
prev = 0
for p in reversed(state): # From biggest disk to smallest
if p != prev:
prev = 3 - p - prev
return p == prev
def next_move(state: list[int]) -> list[int]:
n = len(state)
state = state.copy()
if step_parity(state):
# Time to move the smallest disk
direction = -1 if n % 2 == 1 else 1
state[0] = (state[0] + direction) % 3
return state
else:
# Move the next smallest disk that can be moved
disk_to_move = next(i for i in range(1, n) if state[i] != state[0])
state[disk_to_move] = 3 - state[disk_to_move] - state[0]
return state
def test_all():
answers = (
(
[0, 0, 0],
[2, 0, 0],
[2, 1, 0],
[1, 1, 0],
[1, 1, 2],
[0, 1, 2],
[0, 2, 2],
[2, 2, 2],
), (
[0, 0],
[1, 0],
[1, 2],
[2, 2],
),
)
for answer in answers:
for index, state, next_state in zip(range(len(answer)), answer, answer[1:]):
assert next_move(state) == next_state, f"Failed at index {index}"
assert step_parity(state) == (index % 2 == 0), f"Parity failed at index {index}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment