0

In my attempt to implement a simple version of A* Search, I am trying to enqueue the following in a priority queue:

  • Priority: sum of heuristic value and cost from source to current element
  • Queue Node: Object of class queue node with data members point and cost The code goes something like this: '''s = queueNode(start, 0) q.put((s.dist + heuristics[s.pt[0]][s.pt[1]],s)) # Enqueue source cell'''

However, it gives the following error: in _put heappush(self.queue, item) TypeError: '<' not supported between instances of 'queueNode' and 'queueNode'

Here is the code for class Queue Node

class queueNode:
    def __init__(self, pt, dist: int):
        self.pt = pt  # The cordinates of the cell
        self.dist = dist  # Cell's distance from the source

update: I tried to make the classes comparable by these two Implementations

First

class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return self.dist < other.dist

Second

class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return id(self) < id(other)

it still gives the same error

Update: A workaround to this is to use a list object instead of priority queue and sort it everytime you enter a new element. CODE q=[] APPENDING q.append((heuristics[i][j],queueNodeObject)) SORTING ON BASIS OF COST

def sort(q):
    #start stop step
    for i in range(0,q.__len__(),1):
        for j in range(i+1,q.__len__()-1,1):
            if q[i][0]<q[j][0]:
#q[i] returns the element in queue list i.e tuple=(cost, object) q[i][0] returns #the cost
                temp=q[i]
                q[i]=q[j]
                q[j]=temp
Shahzaib
  • 103
  • 1
  • 11
  • Your class needs to support "comparison". https://stackoverflow.com/questions/6907323/comparable-classes-in-python-3 – Frank Yellin Oct 28 '20 at 19:55
  • Thanks, really helpful. I implemented all the functions in my class queueNode the error still persists though – Shahzaib Oct 28 '20 at 21:46
  • Inside class queueNode you implemented `def __lt__(self, other): ....` and you get the same error message? – Frank Yellin Oct 28 '20 at 22:08
  • @FrankYellin yes, i'll edit the updated code – Shahzaib Oct 28 '20 at 22:13
  • Did you ever post your code in which you implemented __lt__? With all due respect, your sort algorithm is a really slow algorithm. And the whole goal of a heap is that you perform an O(log n) operation after every insertion; you're performing an O(n^2) operation after each insertion. – Frank Yellin Oct 29 '20 at 16:23
  • @FrankYellin Just did – Shahzaib Nov 03 '20 at 05:15

0 Answers0