Question: The python script (check_prefix_codes.py) will read a sequence of codewords from a file and validate if the code is a prefix code. The file codes.txt
The python script ("check_prefix_codes.py") will read a sequence of codewords from a file and validate if the code is a prefix code. The file "codes.txt" is an example input file.
Write a new script that will read two files
- A file containing the codewords (like codes.txt)
- A file containing the sequence of 1s and 0s representing a compressed file, compressed using the code read from the file.
Your script should first validate if the read code is a prefix code, and then use these codewords to decode the second file. (You can assign arbitrary symbols to each codeword).
Put your results and example inputs and outputs in a .pdf file, and submit your scripts along with the example input file(s) used.
codes.txt:
00
01
10
110
111
check_prefix_codes.py:
import numpy as np
class node:
left = None
right = None
isLeaf = False
#read all the codewords from the file
with open('codes.txt', 'r') as inp:
codewords = inp.read().splitlines()
#instantiate the tree
root = node()
for codeword in codewords:
#traverse the tree according to code bits, if you reach a leaf while traversing, output No
marker = root #start from the root
for codebit in codeword:
if marker.isLeaf: #check if marker is a leaf
print("No, the code is not a prefix code")#if yes, output No
quit()else:
if codebit == '0':#if codebit is 0, go left, build if necessary
if marker.left == None: marker.left = node()
marker = marker.left
if codebit == '1':#if codebit is 1, go right, build if necessary
if marker.right == None: marker.right = node()
marker = marker.right
marker.isLeaf = True#make the end point a leaf
print('Yes, the code is a prefix code')
lengths = np.array([len(codeword) for codeword in codewords])
lMean = np.mean(lengths)
print('the average length is %f'%lMean)
Step by Step Solution
There are 3 Steps involved in it
Lets tackle this programming exercise in steps outlining how to write a new script to meet the requirements described Step 1 Validate if the Code is a Prefix Code We will build a function similar to t... View full answer
Get step-by-step solutions from verified subject matter experts
