我正在尝试使用爬山算法解决滑动瓷砖问题。我已经编写了代码来打印每个中间步骤,直到到达目标节点,但代码返回的是内存地址。
from copy import deepcopy
class State:
def __init__(self, state):
goal_state = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]
self.state = state
self.cost = self.calculate_cost(goal_state)
def calculate_cost(self, goal_state):
cost = 0
for i in range(3):
for j in range(3):
if self.state[i][j] != goal_state[i][j]:
cost += 1
return cost
def generate_neighbors(self):
neighbors = []
for i in range(3):
for j in range(3):
if self.state[i][j] == 0:
new_state = deepcopy(self.state)
if i >= 0 and i != 2: #move down
new_state[i][j], new_state[i+1][j] = new_state[i+1][j], new_state[i][j]
neighbors.append(State(new_state))
if i <=2 and i != 0: #move up
new_state[i][j], new_state[i-1][j] = new_state[i-1][j], new_state[i][j]
neighbors.append(State(new_state))
if j >= 0 and j != 2: # move right
new_state[i][j], new_state[i][j+1] = new_state[i][j+1], new_state[i][j]
neighbors.append(State(new_state))
if j <= 2 and j != 0: # move left
new_state[i][j], new_state[i][j-1] = new_state[i][j-1], new_state[i][j]
neighbors.append(State(new_state))
return neighbors
def hill_climbing(initial_state):
current_state = initial_state
while True:
neighbors = current_state.generate_neighbors()
best_neighbor = min(neighbors, key = lambda state: state.cost)
if best_neighbor.cost <= current_state.cost:
print(best_neighbor)
break
print(current_state)
current_state = best_neighbor
initial_state = State([[2, 0, 3], [1, 8, 4], [7, 6, 5]])
hill_climbing(initial_state)
输出:
<__main__.State object at 0x0000021FE103FEE0>
Python 不知道如何打印你的
State
对象,因此它只返回一个内存地址
您可以向
__repr__
类添加 State
方法,该方法将返回类状态的格式化字符串。这是一个示例(您需要添加到您的班级):
def __repr__(self):
# Create a readable string for the state
return '\n'.join([' '.join(map(str, row)) for row in self.state])
__repr__
方法将状态格式化为字符串,其中每行都在新行上,数字之间用空格分隔。一旦你打印了一个 State
对象(就像现在一样),它将显示一个漂亮的格式化字符串而不是内存地址