I am trying to create a tree with the different possible states of the well-known sliding puzzle
In case you don't know it, it's the one like:
[3 5 2]
[4 1]
[8 6 7]
Where you have to make it like this:
[1 2 3]
[4 5 6]
[7 8 ]
Basically, every state generates new states, depending on how the blank space can be moved (upwards, downwards, to the left, or to the right)
What I want is to create the tree with all states given the root as the initial state of the puzzle, but when adding children (new states) to the tree, it should check that that state is not added already anywhere in the tree
Would you mind helping me achieve that? Thanks in advance :)
Here's my current code which throws RecursionError: maximum recursion depth exceeded while calling a Python object
Node class:
class Node(object):
def __init__(self, value, parent=None):
self.parent = parent
self.value = value
self.children = []
def append(self, obj):
if obj is not self.parent and obj not in self.children and obj is not None:
self.children.append(obj)
def has_children(self):
return len(self.children) > 0
def __iter__(self):
yield self.value
for v in chain(*map(iter, self.children)):
yield v
def find_root(self):
p = self
while p.parent is not None:
p = p.parent
return p
Tree generation method (consider self
as a puzzle state):
def to_tree(self, parent=None):
values = []
if parent is not None:
for child in parent.find_root():
values.append(child)
value = nd.Node(self, parent)
if value not in values:
children = [move[1].to_tree(value) for move in self.get_possible_movements()]
for child in children:
if child is not None:
value.append(child)
return value
else:
return None
if value not in values:
statement is always evaluating toTrue
. – Joost