我正在编写一个A *算法(使用Misplaced Tiles启发式)来解决8个难题。当我尝试将Node()
对象添加到优先级队列时,它给出了一个错误" TypeError:unorderable types:Node()<节点()&#34 ;.为什么是这样?
import collections
import queue
import time
class Node:
def __init__(self, puzzle, last=None):
self.puzzle = puzzle
self.last = last
@property
def seq(self): # to keep track of the sequence used to get to the goal
node, seq = self, []
while node:
seq.append(node)
node = node.last
yield from reversed(seq)
@property
def state(self):
return str(self.puzzle.board) # hashable so it can be compared in sets
@property
def isSolved(self):
return self.puzzle.isSolved
@property
def getMoves(self):
return self.puzzle.getMoves
def getMTcost(self):
"""
A* Heuristic where the next node to be expanded is chosen based upon how
many misplaced tiles (MT) are in the state of the next node
"""
totalMTcost = 0
b = self.puzzle.board[:]
# simply +1 if the tile isn't in the goal position
# the zero tile doesn't count
if b[1] != 1:
totalMTcost += 1
if b[2] != 2:
totalMTcost += 1
if b[3] != 3:
totalMTcost += 1
if b[4] != 4:
totalMTcost += 1
if b[5] != 5:
totalMTcost += 1
if b[6] != 6:
totalMTcost += 1
if b[7] != 7:
totalMTcost += 1
if b[8] != 8:
totalMTcost += 1
return totalMTcost
class Solver:
def __init__(self, Puzzle):
self.puzzle = Puzzle
def FindLowestMTcost(NodeList):
print(len(NodeList))
lowestMTcostNode = NodeList[0]
lowestMTcost = lowestMTcostNode.getMTcost()
for i in range(len(NodeList)):
if NodeList[i].getMTcost() < lowestMTcost:
lowestMTcostNode = NodeList[i]
return lowestMTcostNode # returns Node object
def AStarMT(self):
visited = set()
myPQ = queue.PriorityQueue(0)
myPQ.put((0, Node(self.puzzle))) # Accepted here???
while myPQ:
closetChild = myPQ.get()[1]
visited.add(closetChild.state)
for board in closetChild.getMoves:
newChild = Node(board, closetChild)
if newChild.state not in visited:
if newChild.getMTcost() == 0:
return newChild.seq
priority_num = newChild.getMTcost()
myPQ.put((priority_num, newChild)) # ERROR HERE
答案 0 :(得分:2)
我猜你正在推动具有相同优先级的两个节点。由于您的PriorityQueue
项是priority, Node
元组,因此元组的比较将首先检查优先级,并且只有它们相等才会比较Node
s。
解决此问题的方法是在元组中提供额外的打破平局值。一个稳定增加的计数器是一个常见的联系断路器(但如果你想让较新的节点在较旧的节点之前进行排序,则考虑减少数量):
myPQ = queue.PriorityQueue()
count = 0
# later, when you add to the queue:
myPQ.put((priority_num, count, newChild))
count += 1
如果您不想手动递增计数器,可以使用itertools.count
,这会产生无限增加值的生成器。只要您需要新值,就可以使用count = itertools.count()
然后使用next(count)
。
最后一点说明:您正在使用PriorityQueue
模块中的queue
类。该模块设计用于线程间通信,而不是真正用于通用数据结构。它会做一堆你真正不关心的锁定东西。更好的方法是使用heapq
模块从列表中创建优先级队列:
import heapq
# create the queue (a regular list)
my_queue = []
# push to the queue
heapq.heappush(my_queue, (priority, tie_breaker, value))
# pop from the queue
result_priority, _, result_value = heapq.heappop(my_queue)