SlideShare a Scribd company logo
edit ONLY the function to make the test case pass
#huffman.py
from __future__ import annotations
from typing import Optional, TextIO
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 huffman_encode(in_file: TextIO, out_file: TextIO) -> None:
"""Encode the data in the input file.
This will write its result to the output file and won't return
anything.
"""
freqs = count_frequencies(in_file)
tree = build_huffman_tree(freqs)
codes = create_codes(tree)
header = create_header(freqs)
out_file.write(header + "n")
in_file.seek(0)
bit_buffer = 0
bit_count = 0
for byte in in_file.read():
code = codes[ord(byte)]
for bit in code:
bit_buffer <<= 1
if bit == '1':
bit_buffer |= 1
bit_count += 1
if bit_count == 8:
#out_file.write(chr(bit_buffer))
out_file.write(str(bytes([bit_buffer])))
#out_file.write(bytes([bit_buffer]).decode('ISO-8859-1'))
#out_file.buffer.write(bytes([bit_buffer]))
#out_file.write(str(bytes([bit_buffer]), 'latin-1'))
bit_buffer = 0
bit_count = 0
if bit_count > 0:
bit_buffer <<= (8 - bit_count)
#out_file.write(chr(bit_buffer))
out_file.write(str(bytes([bit_buffer])))
#out_file.write(bytes([bit_buffer]).decode('ISO-8859-1'))
#out_file.buffer.write(bytes([bit_buffer]))
#out_file.write(str(bytes([bit_buffer]), 'latin-1'))
#huffman_tests.py
def test_huffman_encode_01(self) -> None:
# Create fake files to use for testing
in_file = io.StringIO("abcd abc ab a")
out_file = io.StringIO()
huffman_encode(in_file, out_file)
result = out_file.getvalue()
in_file.close()
out_file.close()
correct_out_text = (
"32 3 97 4 98 3 99 2 100 1n11011011000011011010011010011"
)
self.assertEqual(result, correct_out_text)
in test_huffman_encode_01
self.assertEqual(result, correct_out_text)
AssertionError: "32 3 97 4 98 3 99 2 100 1nb'xdb'b'r'b'xa6'b'x98'" != '32 3 97 4 98 3 99 2
100 1n11011011000011011010011010011'
32 3 97 4 98 3 99 2 100 1
- b'xdb'b'r'b'xa6'b'x98'+ 11011011000011011010011010011

More Related Content

More from ConnorryKPooler

Drag and drop options on the right-hand side and submit- For keyboard.docx
Drag and drop options on the right-hand side and submit- For keyboard.docxDrag and drop options on the right-hand side and submit- For keyboard.docx
Drag and drop options on the right-hand side and submit- For keyboard.docx
ConnorryKPooler
 
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docx
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docxDoes DNA polymerase travel back from the cytoplasm into the nucleus th.docx
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docx
ConnorryKPooler
 
Donna and I have an agreement that she will come to clean my house on.docx
Donna and I have an agreement that she will come to clean my house on.docxDonna and I have an agreement that she will come to clean my house on.docx
Donna and I have an agreement that she will come to clean my house on.docx
ConnorryKPooler
 
Diseases of yersinia genus (species) -.docx
Diseases of yersinia genus (species) -.docxDiseases of yersinia genus (species) -.docx
Diseases of yersinia genus (species) -.docx
ConnorryKPooler
 
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docxExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
ConnorryKPooler
 
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docxExercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
ConnorryKPooler
 
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docxExercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
ConnorryKPooler
 
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docxExercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
ConnorryKPooler
 
Exercise 2- Describe the difference between allocative efficiency and.docx
Exercise 2- Describe the difference between allocative efficiency and.docxExercise 2- Describe the difference between allocative efficiency and.docx
Exercise 2- Describe the difference between allocative efficiency and.docx
ConnorryKPooler
 
Discrete data is data that can be represented by any number- including (1).docx
Discrete data is data that can be represented by any number- including (1).docxDiscrete data is data that can be represented by any number- including (1).docx
Discrete data is data that can be represented by any number- including (1).docx
ConnorryKPooler
 
Example Students at a major university in NY are complaining about a s.docx
Example Students at a major university in NY are complaining about a s.docxExample Students at a major university in NY are complaining about a s.docx
Example Students at a major university in NY are complaining about a s.docx
ConnorryKPooler
 
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docxEvolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
ConnorryKPooler
 
Evolution has a way of resulting in unrelated animals building structu.docx
Evolution has a way of resulting in unrelated animals building structu.docxEvolution has a way of resulting in unrelated animals building structu.docx
Evolution has a way of resulting in unrelated animals building structu.docx
ConnorryKPooler
 
Euter inferinesinen-Cether mine mever Eequered 4).docx
Euter inferinesinen-Cether mine mever Eequered 4).docxEuter inferinesinen-Cether mine mever Eequered 4).docx
Euter inferinesinen-Cether mine mever Eequered 4).docx
ConnorryKPooler
 
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docxEubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
ConnorryKPooler
 
Essential is Human Resources please a new answer not one listed Why is.docx
Essential is Human Resources please a new answer not one listed Why is.docxEssential is Human Resources please a new answer not one listed Why is.docx
Essential is Human Resources please a new answer not one listed Why is.docx
ConnorryKPooler
 
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docxEnzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
ConnorryKPooler
 
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docxEquipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
ConnorryKPooler
 
Environmental disease refers to any pathologic process that is a conse.docx
Environmental disease refers to any pathologic process that is a conse.docxEnvironmental disease refers to any pathologic process that is a conse.docx
Environmental disease refers to any pathologic process that is a conse.docx
ConnorryKPooler
 
Entity B records transactions that change its financial statements in.docx
Entity B records transactions that change its financial statements in.docxEntity B records transactions that change its financial statements in.docx
Entity B records transactions that change its financial statements in.docx
ConnorryKPooler
 

More from ConnorryKPooler (20)

Drag and drop options on the right-hand side and submit- For keyboard.docx
Drag and drop options on the right-hand side and submit- For keyboard.docxDrag and drop options on the right-hand side and submit- For keyboard.docx
Drag and drop options on the right-hand side and submit- For keyboard.docx
 
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docx
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docxDoes DNA polymerase travel back from the cytoplasm into the nucleus th.docx
Does DNA polymerase travel back from the cytoplasm into the nucleus th.docx
 
Donna and I have an agreement that she will come to clean my house on.docx
Donna and I have an agreement that she will come to clean my house on.docxDonna and I have an agreement that she will come to clean my house on.docx
Donna and I have an agreement that she will come to clean my house on.docx
 
Diseases of yersinia genus (species) -.docx
Diseases of yersinia genus (species) -.docxDiseases of yersinia genus (species) -.docx
Diseases of yersinia genus (species) -.docx
 
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docxExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
ExERCise 6- Below is a Venn diagram organizing survey data on people w.docx
 
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docxExercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
Exercise 5 - Test Your Knowledge 1) Sectioned Long Bone Use choices be.docx
 
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docxExercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
Exercise 4-4 (Algo) Multiple-step continuous statement of comprehensiv.docx
 
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docxExercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
Exercise 5 - Sparse Matrices A simple way to represent a matrix is via.docx
 
Exercise 2- Describe the difference between allocative efficiency and.docx
Exercise 2- Describe the difference between allocative efficiency and.docxExercise 2- Describe the difference between allocative efficiency and.docx
Exercise 2- Describe the difference between allocative efficiency and.docx
 
Discrete data is data that can be represented by any number- including (1).docx
Discrete data is data that can be represented by any number- including (1).docxDiscrete data is data that can be represented by any number- including (1).docx
Discrete data is data that can be represented by any number- including (1).docx
 
Example Students at a major university in NY are complaining about a s.docx
Example Students at a major university in NY are complaining about a s.docxExample Students at a major university in NY are complaining about a s.docx
Example Students at a major university in NY are complaining about a s.docx
 
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docxEvolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
Evolutionary Ties Between Molluses- Annelids- and Arthropods In older.docx
 
Evolution has a way of resulting in unrelated animals building structu.docx
Evolution has a way of resulting in unrelated animals building structu.docxEvolution has a way of resulting in unrelated animals building structu.docx
Evolution has a way of resulting in unrelated animals building structu.docx
 
Euter inferinesinen-Cether mine mever Eequered 4).docx
Euter inferinesinen-Cether mine mever Eequered 4).docxEuter inferinesinen-Cether mine mever Eequered 4).docx
Euter inferinesinen-Cether mine mever Eequered 4).docx
 
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docxEubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
Eubacteria- Bacteria and Cyanobacteria Internet Search and Microscopy.docx
 
Essential is Human Resources please a new answer not one listed Why is.docx
Essential is Human Resources please a new answer not one listed Why is.docxEssential is Human Resources please a new answer not one listed Why is.docx
Essential is Human Resources please a new answer not one listed Why is.docx
 
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docxEnzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
Enzymes can only function in a narrow pH range- 1) True 2) FalseChoose.docx
 
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docxEquipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
Equipment 42-000 Capital 41-000 Accounts payable 12-000 Interest incom.docx
 
Environmental disease refers to any pathologic process that is a conse.docx
Environmental disease refers to any pathologic process that is a conse.docxEnvironmental disease refers to any pathologic process that is a conse.docx
Environmental disease refers to any pathologic process that is a conse.docx
 
Entity B records transactions that change its financial statements in.docx
Entity B records transactions that change its financial statements in.docxEntity B records transactions that change its financial statements in.docx
Entity B records transactions that change its financial statements in.docx
 

Recently uploaded

NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
Payaamvohra1
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
heathfieldcps1
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
TechSoup
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
Celine George
 
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
indexPub
 
adjectives.ppt for class 1 to 6, grammar
adjectives.ppt for class 1 to 6, grammaradjectives.ppt for class 1 to 6, grammar
adjectives.ppt for class 1 to 6, grammar
7DFarhanaMohammed
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
Kalna College
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
 
Ch-4 Forest Society and colonialism 2.pdf
Ch-4 Forest Society and colonialism 2.pdfCh-4 Forest Society and colonialism 2.pdf
Ch-4 Forest Society and colonialism 2.pdf
lakshayrojroj
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
Nguyen Thanh Tu Collection
 
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGHKHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
shreyassri1208
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
MJDuyan
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
OH TEIK BIN
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
nitinpv4ai
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
EduSkills OECD
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 

Recently uploaded (20)

NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
 
The basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptxThe basics of sentences session 7pptx.pptx
The basics of sentences session 7pptx.pptx
 
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...
 
How to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in useHow to Fix [Errno 98] address already in use
How to Fix [Errno 98] address already in use
 
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
 
adjectives.ppt for class 1 to 6, grammar
adjectives.ppt for class 1 to 6, grammaradjectives.ppt for class 1 to 6, grammar
adjectives.ppt for class 1 to 6, grammar
 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
 
Ch-4 Forest Society and colonialism 2.pdf
Ch-4 Forest Society and colonialism 2.pdfCh-4 Forest Society and colonialism 2.pdf
Ch-4 Forest Society and colonialism 2.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 8 - CẢ NĂM - FRIENDS PLUS - NĂM HỌC 2023-2024 (B...
 
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGHKHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
KHUSWANT SINGH.pptx ALL YOU NEED TO KNOW ABOUT KHUSHWANT SINGH
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
 
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptxA Free 200-Page eBook ~ Brain and Mind Exercise.pptx
A Free 200-Page eBook ~ Brain and Mind Exercise.pptx
 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
 
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 

edit ONLY the function to make the test case pass #huffman-py from.docx

  • 1. edit ONLY the function to make the test case pass #huffman.py from __future__ import annotations from typing import Optional, TextIO 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
  • 2. 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 huffman_encode(in_file: TextIO, out_file: TextIO) -> None: """Encode the data in the input file. This will write its result to the output file and won't return
  • 3. anything. """ freqs = count_frequencies(in_file) tree = build_huffman_tree(freqs) codes = create_codes(tree) header = create_header(freqs) out_file.write(header + "n") in_file.seek(0) bit_buffer = 0 bit_count = 0 for byte in in_file.read(): code = codes[ord(byte)] for bit in code: bit_buffer <<= 1 if bit == '1': bit_buffer |= 1 bit_count += 1 if bit_count == 8: #out_file.write(chr(bit_buffer)) out_file.write(str(bytes([bit_buffer]))) #out_file.write(bytes([bit_buffer]).decode('ISO-8859-1')) #out_file.buffer.write(bytes([bit_buffer]))
  • 4. #out_file.write(str(bytes([bit_buffer]), 'latin-1')) bit_buffer = 0 bit_count = 0 if bit_count > 0: bit_buffer <<= (8 - bit_count) #out_file.write(chr(bit_buffer)) out_file.write(str(bytes([bit_buffer]))) #out_file.write(bytes([bit_buffer]).decode('ISO-8859-1')) #out_file.buffer.write(bytes([bit_buffer])) #out_file.write(str(bytes([bit_buffer]), 'latin-1')) #huffman_tests.py def test_huffman_encode_01(self) -> None: # Create fake files to use for testing in_file = io.StringIO("abcd abc ab a") out_file = io.StringIO() huffman_encode(in_file, out_file) result = out_file.getvalue() in_file.close() out_file.close() correct_out_text = (
  • 5. "32 3 97 4 98 3 99 2 100 1n11011011000011011010011010011" ) self.assertEqual(result, correct_out_text) in test_huffman_encode_01 self.assertEqual(result, correct_out_text) AssertionError: "32 3 97 4 98 3 99 2 100 1nb'xdb'b'r'b'xa6'b'x98'" != '32 3 97 4 98 3 99 2 100 1n11011011000011011010011010011' 32 3 97 4 98 3 99 2 100 1 - b'xdb'b'r'b'xa6'b'x98'+ 11011011000011011010011010011