Skip to content

Instantly share code, notes, and snippets.

@mlazos
Created September 21, 2025 08:48
Show Gist options
  • Select an option

  • Save mlazos/d538281dfc7a75a63d629b5a8f1fc1b7 to your computer and use it in GitHub Desktop.

Select an option

Save mlazos/d538281dfc7a75a63d629b5a8f1fc1b7 to your computer and use it in GitHub Desktop.
'''
Online Python Interpreter.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
from dataclasses import dataclass
from collections import deque
from copy import deepcopy
# blocks
problem1 = ([['A', 'B', 'C'], ['D', 'E']], [['B', 'C', 'A'], ['D', 'E']])
@dataclass
class State:
top_to_stack: dict[str, list[str]]
stacks: list[list[str]]
@staticmethod
def from_problem(problem):
cur_state, _ = problem
cur_state = deepcopy(cur_state)
top_to_stack = {stack[-1] : stack for stack in cur_state}
return State(top_to_stack, cur_state)
def move(self, top_block, dst_top_block):
stack = self.top_to_stack.pop(top_block)
block = stack.pop()
# If src stack is now empty, don't add back
if len(stack) > 0:
self.top_to_stack[stack[-1]] = stack
else:
self.stacks = [s for s in self.stacks if len(s) > 0]
if dst_top_block is None:
new_stack = [block]
self.top_to_stack[block] = new_stack
self.stacks.append(new_stack)
else:
dst_stack = self.top_to_stack[dst_top_block]
dst_stack.append(block)
self.top_to_stack.pop(dst_top_block)
self.top_to_stack[block] = dst_stack
def move_inverse(self, src, origin):
self.move(src, origin)
def all_moves(self):
srcs = list(self.top_to_stack.keys())
dsts = list(self.top_to_stack.keys()) + [None]
result = []
for src in srcs:
for dst in dsts:
if src != dst:
result.append((src, dst, self.get_src_constraint(src)))
return result
def get_src_constraint(self, src):
# allows us to invert moves
stack = self.top_to_stack[src]
if len(stack) > 1:
return stack[-2]
else:
return None # empty table remains
state = State.from_problem(problem1)
print(state)
state.move("C", "E")
print(state)
state.move_inverse("C", "B")
print(state)
def solve_bfs(problem):
_, goal = problem
state = State.from_problem(problem)
queue = deque(state.all_moves())
while queue:
move = queue.popleft()
state.move(*move)
if state.stacks == goal:
break
queue.extend(state.all_moves())
def solve(prob):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment