Skip to content Skip to sidebar Skip to footer

Getting "not Supported Between Instances Of 'tuple' And 'list'" When Adding Object To Priority Queue

Im trying to add a pair of elements to a priority queue. When I try to add an element im getting this error: 'TypeError: < not supported between instances of 'tuple' and 'list''

Solution 1:

I've found the culprit behind the error :).

The way the queue.PriorityQueue class works is by storing a list of items. Whenever you .put something in, it will compare it using < and > to find the spot to insert it into. '.get' will simply pop it out from the already sorted list.

Because of the fact that the tuple and list cannot be compared, the .put fails. This may also be because you can change the list after, causing the priority queue to break.

A simple fix is to change the line in repsInS with freqs.append([t, reps]) into freqs.append((t, reps)).

EDIT: Looks like there's more... The priority queue orders them using the object's rich comparison magic methods. Instead, I've made them use a normal list and have the Node save its own weight. This saves complexity in the class and makes the code more understandable.

Here is the fixed and polished code.

import queue

test_str = 'testString'
test_list = [chr(i) for i inrange(ord('a'), ord('z') + 1)]


classHuffmanNode:
    def__init__(self, weight, left=None, right=None, info=None):
        self.weight = weight
        self.left = left
        self.right = right
        self.info = info

    defhijoTemp(self):
        return self.left, self.right


defget_repeats(S, T):
    freqs = []

    for t in T:
        reps = 0for s in S:
            if s == t:
                reps += 1
        freqs.append((reps, t))

    freqs.sort(key=lambda x: x[0], reverse=True)
    return freqs # Return list of listsdefcreate_huffman_tree(freqs):
    objs = [HuffmanNode(w, info=l) for w, l in freqs]
    objs.sort(key=lambda node: node.weight, reverse=True)

    whilelen(objs) > 1:
        left, right = objs.pop(), objs.pop()
        weight = left.weight + right.weight
        objs.put(HuffmanNode(weight, left, right))

    return objs.pop()

if __name__ == '__main__':
    frecuencias = get_repeats(test_str, test_list)
    huffman_tree = create_huffman_tree(frecuencias)

Post a Comment for "Getting "not Supported Between Instances Of 'tuple' And 'list'" When Adding Object To Priority Queue"