Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a priority queue using heapq for Huffman nodes.
DSA Python
import heapq heap = [] heapq.[1](heap, (frequency, symbol))
Attempts:
3 left
💡 Hint
Common Mistakes
Using push instead of heappush causes AttributeError.
Using insert or add are not valid heapq functions.
✗ Incorrect
The heapq module uses heappush to add elements to the heap (priority queue).
2fill in blank
mediumComplete the code to pop the smallest frequency node from the heap.
DSA Python
frequency, symbol = heapq.[1](heap)Attempts:
3 left
💡 Hint
Common Mistakes
Using pop causes IndexError or wrong behavior.
remove and extract are not heapq functions.
✗ Incorrect
heapq.heappop(heap) removes and returns the smallest element from the heap.
3fill in blank
hardFix the error in the code to combine two nodes into a new Huffman node.
DSA Python
combined_freq = left[0] [1] right[0] combined_node = (combined_freq, left, right)
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication or division changes the frequency meaning.
Subtracting frequencies can cause negative values.
✗ Incorrect
In Huffman encoding, frequencies are added to combine nodes.
4fill in blank
hardFill both blanks to build the Huffman tree by popping two smallest nodes and pushing their combination.
DSA Python
left = heapq.[1](heap) right = heapq.[2](heap) combined = (left[0] + right[0], left, right) heapq.heappush(heap, combined)
Attempts:
3 left
💡 Hint
Common Mistakes
Using heappush instead of heappop to get nodes causes errors.
Using pop or push are not valid heapq functions.
✗ Incorrect
We pop two smallest nodes using heappop twice before pushing the combined node.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that assigns codes to symbols recursively.
DSA Python
codes = {symbol: code for symbol, code in [1](node, [2]) if symbol is not None and len(code) > 0}
def [3](node, prefix):
if isinstance(node[1], tuple):
yield from [3](node[1], prefix + '0')
yield from [3](node[2], prefix + '1')
else:
yield (node[1], prefix)Attempts:
3 left
💡 Hint
Common Mistakes
Using codes.items() or items is incorrect here.
Not passing empty string as prefix causes wrong codes.
✗ Incorrect
The dictionary comprehension calls traverse with the root node and empty prefix string. The function named traverse recursively yields symbol-code pairs.
