我正在实施最佳的首次搜索和A *算法来解决8件式拼图程序,但首先需要验证状态是否可解决。
要查找状态是否可解决,我使用了反转次数和该次数的奇偶校验。请查看here有关查找可解状态的更多信息。
我的问题位于可解决的函数之内:
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
现在,它只返回总数,因此我可以在返回基本的true或false之前检查它是否在计算正确的值。
我用来创建状态并在该状态上可调用的简单脚本是:
1 import tempStateController as sc
2 obj = sc.State([5,4,3],[2,1,7],[8,0,6])
3 obj.solvable()
我遇到的错误如下:
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
这是我完整的stateController代码:
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
这里快速介绍了如何查找状态的反转次数:
任何帮助将不胜感激!谢谢。
答案 0 :(得分:3)
您有错字。您已经传递了三个列表:
obj = sc.State([5,4,3],[2,1,7],[8,0,6])
而不是列表列表:
obj = sc.State([[5,4,3],[2,1,7],[8,0,6]])
state
等于[5,4,3]
,因此self.state[row2]
等于5
。有效地使5[column2]
返回int not subscriptable
。