python - 在 Python 上实现深度搜索策略时出错
问题描述
我正在尝试编写一个使用python和深度搜索策略解决8个难题的代码,但由于某种原因,如果有人可以帮助我,我在错误处理中遇到错误,这是代码和错误
代码
from simpleai.search import SearchProblem, astar
GOAL = '''1-2-3
4-5-6
7-8-e'''
INITIAL = '''4-5-1
8-3-7
e-6-2'''
def list_to_string(list_):
return '\n'.join(['-'.join(row) for row in list_])
def string_to_list(string_):
return [row.split('-')for row in string_.split('\n')]
def find_location(rows, element_to_find):
for ir, row in enumerate(rows):
for ic, element in enumerate(rows):
if element == element_to_find:
return ir, ic
goal_positions ={}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
goal_positions[number] = find_location(rows_goal, number)
class EightPulzzeProblem(SearchProblem):
def actions(self, state):
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e > 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e > 2:
actions.append(rows[row_e][col_e + 1])
return actions
def result(self, state, action):
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, action)
rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[row_e][col_e]
return list_to_string(rows)
def is_goal(self, state):
return state == GOAL
def heuristic(self, state):
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
row_n_goal, col_n_goal = goal_positions[number]
distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)
return distance
result = astar(EightPulzzeProblem(INITIAL))
for action, state, in result.path():
print ('mover el numero ', action)
print (state)
错误
NotImplementedError Traceback (most recent call last)
<ipython-input-4-08487032cc77> in <module>()
69
70
---> 71 result = astar(EightPulzzeProblem(INITIAL))
72 for action, state, in result.path():
73 print ('mover el numero ', action)
2 frames
/usr/local/lib/python3.7/dist-packages/simpleai/search/models.py in is_goal(self, state)
39 def is_goal(self, state):
40 '''Returns `True` if `state` is a goal state and `False` otherwise'''
---> 41 raise NotImplementedError
42
43 def value(self, state):
NotImplementedError:
我尝试将错误处理放在 def 是目标,但我在代码上遇到了同样的错误
解决方案
推荐阅读
- python - 在 Python 中使用 InfluxDB 差分函数
- apache-spark - 缓存 pyspark 数据帧不会导致性能提升
- c++ - 错误:字符串之前的预期主表达式
- c++ - 如何在 C++ 中使用 unsigned char 数组创建 streambuf
- math - 如何计算箭头填充时钟所有给定扇区所需的步数?
- c# - 如何使用 C# 进行 OAuth 1 Twitter API 调用(dotnet core 3.1)
- python - 从Python中的excel文件填充空单元格并重命名多索引标题的列名
- c# - 有没有办法代替双重不冻结项目,而是说无效号码?
- html - 为什么不使用最高的 z-index 允许我的图标覆盖应该在它下面的 div 但它不会?
- gremlin - 通过另一个顶点查询顶点 [GREMLIN]