首页 > 解决方案 > 在 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 是目标,但我在代码上遇到了同样的错误

标签: pythonerror-handlingkotlin.notimplementederror

解决方案


推荐阅读