def build_huffman_tree(frequency_table: dict[str, int]) -> Node: priority_queue = Priority_Queue() for symbol in frequency_table: priority_queue.insert(Node(priority=frequency_table[symbol], symbol=symbol)) while len(priority_queue) > 1: left_child = priority_queue.pull() right_child = priority_queue.pull() combined_priority = left_child.priority + right_child.priority priority_queue.insert(Node(priority=combined_priority, left_child=left_child, right_child=right_child)) return priority_queue.pull()
def test_peek(m_eq, m_lbh, m_hbl): assert isinstance(m_eq.peek(), type(None)) assert m_lbh.peek() == -1 assert m_hbl.peek() == -1 # Only low priority items in the list. q = Priority_Queue(2) q.insert('eh', 1) assert q.peek() == 'eh' q.insert('again', 1) assert q.peek() == 'eh'
def m_hbl(request): q = Priority_Queue(2) for x in range(-1, -6, -1): q.insert(x, 0) for x in range(5): q.insert(x, 1) return q
def test_pop(m_eq, m_lbh, m_hbl): # pop() an empty Priority_Queue. with pytest.raises(IndexError): m_eq.pop() # Low before high priority and high before low enqueued should not # affect the order of these when popped off for x in range(-1, -6, -1): assert m_lbh.pop() == x assert m_hbl.pop() == x for x in range(5): assert m_lbh.pop() == x assert m_hbl.pop() == x # Only high priority items in the list. q = Priority_Queue(2) q.insert('hey', 0) q.insert('last', 0) assert q.pop() == 'hey' assert q.pop() == 'last'
def populated_queue(): pq = Priority_Queue() pq.insert(PNode(100, 10)) pq.insert(PNode(150, 1)) pq.insert(PNode("Hello", 30)) pq.insert(PNode("first_2000", 2000)) pq.insert(PNode("second_2000", 2000)) return pq
def pop_off_empty_queue(): pq = Priority_Queue() with pytest.raises(IndexError): pq.pop()
def test_insert_into_empty_queue(): pq = Priority_Queue() pq.insert(PNode("thirty", 30)) assert pq.peek() == "thirty"
def m_eq(request): return Priority_Queue(2)
def test_insert_into_empty_queue(): pq = Priority_Queue() pq.insert(PNode('thirty', 30)) assert pq.peek() == 'thirty'