Reputation: 55
I am implementing a best first search and A* algorithms to solve the 8-piece puzzle program, but first need to verify if a state is solvable or not.
To find if a state is solvable or not I use the number of inversions and the parity of that number. Look here more information on finding solvable states.
My question resides inside the solvable function:
20 def solvable(self):
21 total=0
22 for i in range(8):
23 step = i+1
24 row = i//3
25 col = i%3
26 print("row: ",row," col: ",col)
27 value = int(self.state[row][col])
28 for j in range(step,9):
29 row2 = i//3
30 col2 = i%3
31 value2 = self.state[row2][column2]
32 if not value2==0 and value2>value:
33 total+=1
34 return total
Right now, it just returns the total so I can check that it is computing the right value before I return a basic true or false.
The simple script I use to create a state and call solvable on that state is:
1 import tempStateController as sc
2 obj = sc.State([5,4,3],[2,1,7],[8,0,6])
3 obj.solvable()
The error that I am running into looks like:
Traceback (most recent call last):
File "test.py", line 3, in <module>
obj.solvable()
File "/home/colin/Documents/gradSchool/spring2019/ai/hw/bestFirstAStar/tempStateController.py", line 27, in solvable
value = int(self.state[row][col])
TypeError: 'int' object is not subscriptable
Here is my complete stateController code:
1 #this is a generic state class that holds the values of each
2 #position in the environment class State:
3 class State:
4 parent=None
5 children=[]
6 cost=0
7 ID=0
8
9 state = [[0,0,0],[0,0,0],[0,0,0]]
10
11 def __init__(self,state,parent=None,children=None):
12 self.state = state
13 self.parent = parent
14 if children:
15 self.children = children
16
17 #check a state is solvable
18 def solvable(self):
19 total=0
20 for i in range(8):
21 step = i+1
22 row = i//3
23 col = i%3
24 print("row: ",row," col: ",col)
25 value = int(self.state[row][col])
26 for j in range(step,9):
27 row2 = i//3
28 col2 = i%3
29 value2 = self.state[row2][column2]
30 if not value2==0 and value2>value:
31 total+=1
32 return total
Here is a quick walk through of how to find the number of inversions for a state:
Any help is greatly appreciated! Thanks.
Upvotes: 2
Views: 149
Reputation: 177745
You have a typo. You've passed three lists:
obj = sc.State([5,4,3],[2,1,7],[8,0,6])
instead of a list of lists:
obj = sc.State([[5,4,3],[2,1,7],[8,0,6]])
state
equals [5,4,3]
, so self.state[row2]
equals 5
. Effectively making 5[column2]
return int not subscriptable
.
Upvotes: 3