Question: fix the error for the function that's failing the test case #huffman.py class HuffmanNode: A node in a Huffman tree. Attributes: char: The character as

fix the error for the function that's failing the test case

#huffman.py

class HuffmanNode:

"""A node in a Huffman tree.

Attributes:

char: The character as an integer ASCII value

frequency: The frequency of the character in the file

left: The left Huffman sub-tree

right: The right Huffman sub-tree

"""

def __init__(

self, char: int, frequency: int, left: HuffmanTree, right: HuffmanTree

):

self.char = char

self.frequency = frequency

self.left = left

self.right = right

def __eq__(self, other) -> bool:

"""Return True if and only if self and other are equal."""

if isinstance(other, HuffmanNode):

return (

self.char == other.char

and self.frequency == other.frequency

and self.left == other.left

and self.right == other.right

)

return False

def __lt__(self, other) -> bool:

"""Return True if and only if self < other."""

if isinstance(other, HuffmanNode):

return self.frequency < other.frequency

return False

HuffmanTree = Optional[HuffmanNode]

def build_huffman_tree(frequencies: list[int]) -> HuffmanTree:

"""Create a Huffman tree of the characters with non-zero frequency.

Returns the root of the tree.

"""

try:

nodes = [(f, HuffmanNode(i, f, None, None)) for i, f in enumerate(frequencies) if f > 0]

while len(nodes) > 1:

nodes.sort()

left = nodes.pop(0)[1]

right = nodes.pop(0)[1]

parent = HuffmanNode(None, left.frequency + right.frequency, left, right)

nodes.append((parent.frequency, parent))

return nodes[0][1] if nodes else None

except (TypeError, ValueError) as e:

print(f"Error: {e}")

return None

#huffman_tests.py

def test_build_huffman_tree_01(self) -> None:

frequencies = [0] * 256

frequencies[97] = 5

frequencies[98] = 10

huffman_tree = build_huffman_tree(frequencies)

# NOTE: This also requires a working __eq__ for your HuffmanNode

self.assertEqual(

huffman_tree,

HuffmanNode(

97,

15,

HuffmanNode(97, 5, None, None),

HuffmanNode(98, 10, None, None),

),

)

in test_build_huffman_tree_01 self.assertEqual( AssertionError: !=

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!