I have an simple brute force AI code for the 8 puzzle problem. One of the steps involves checking if the current state has already been visited, and all the visited states are stored in a list called visited = [].
I noticed my program was taking too long to find the solution, and started using wall time checks to see what functions were taking the longest. To my surprise, the built in sorting algorithm was using almost 35 seconds, and had to sort through a maximum of 21000 elements at a time.
On the other hand, my visited list reached a maximum length of 42000. (I'm appending Class objects to this visited list as explained below)
Every time a new state is generated, it is compared with all the states in the visited list to check if it already exists there using the not_in method.
def not_in(self, visited):
for node in visited:
if (self.data == node.data):
return 0
return 1
This checks if the currently passed in Node has its Node.data equal to any other Node in the visited list.
The caller function looks like this -
if Node.not_in(temp_right, visited):
visited.append(temp_right)
where self refers to a class object of the following type-
class Node:
def __init__(self, data, parent):
self.data = data
self.parent = parent
where self.data is a list, and self.parent refers to another class object Node, like a linked list.
This not_in function has to perform over 1366241896 comparisons to reach the solution from my current starting state.
Is there a way to optimize this function? Because that's a lot of comparisons that I'd like to avoid. The whole program exclusively uses lists to store data, if that helps my case.