Melissa Stewart
Melissa Stewart

Reputation: 3605

Custom comparator in Python

I'm trying to write a custom comparator in Python, that compares two node objects based on the following rules 1. Least frequency 2. Shortest length 3. Lexicographic ordering.

Here's my node object

class Node:
    def __init__(self, key: str, value: int):
        self.key = key
        self.value = value

This is my Comparator

class Comparator:
    def __init__(self, node):
        self.node = node

    def __lt__(self, other):
        if self.node.value > other.value:
            return True
        elif len(self.node.key) > len(other.key):
            return True
        elif self.node.key > other.key:
            return True

I'm trying to use this Comparator to push node items to a heap, this is my code,

frequency_map = Counter(string)
        for k, v in frequency_map.items():
            p = Node(k, v)
            heapq.heappush(self.heap, Comparator(p))

This throws up the following error,

AttributeError: 'Comparator' object has no attribute 'value'

What am I doing wrong here?

Upvotes: 0

Views: 1911

Answers (1)

David Maze
David Maze

Reputation: 158898

Inside your Comparator class:

def __lt__(self, other):
    if self.node.value > other.value:
        return True

Both self and other are instances of Comparator (Python has no way of knowing this is just an object wrapper) and you need to check other.node.value.

Upvotes: 2

Related Questions