0

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)]

  • I guess you could write a function that returns the value if the variable is a tuple, or the weight if the variable is a tree, then use it as a sorting key. Oh well, I just saw you did exactly that :) Good job then. – Swifty Apr 03 '23 at 19:45

1 Answers1

2

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)
Swifty
  • 2,630
  • 2
  • 3
  • 21