How to sort a heterogeneous list of Tree Objects and Tuples

53 Views Asked by At

How would I sort a list of tuple and tree objects? I have list of tuples (key: str, value: frequency), and huffman tree objects where the tree has a left, right, symbol and weight attributes, I would like to initially sort the list by the tuple's values (which I have already done with sorted), however I'm not sure if there is a way to sort the list after appending huffman tree objects and sorting by the tree's weight and tuple's value - heterogeneously?

I want to pop the two lowest frequency elements from the list and create a huffman tree from those two values, then re-add the tree to the list - sort the list again (this time with trees and tuples), and repeat.

sorted_freq = [] for element in freq_dict: element_in_tuple_form = (element, freq_dict[element]) sorted_freq.append(element_in_tuple_form) sorted_freq = sorted(sorted_freq, key=lambda x: x[1], reverse=False)

sort_me = [("a", 1), ("b", 3), HuffmanTree(2)] sort_me = sorted(...) print(sort_me) >>> [("a", 1), HuffmanTree(2), ("b", 3)]

1

There are 1 best solutions below

1
Yusuf Gökçe On

I figured that writing your own key method for sorted resolves this issue.

def sort_by_weight_and_key(obj: Optional[tuple, HuffmanTree]) -> int:
   if isinstance(obj, tuple):
      return obj[1]
   elif isinstance(obj, HuffmanTree):
      return HuffmanTree.weight
   else:
      raise TypeError

this allowed me to use sorted using sort_by_weight_and_key as my key.

sort_me = sorted(sort_me, key=sort_by_weight_and_key, reverse=False)