Created
January 13, 2024 16:04
-
-
Save salvatorecapolupo/558151eba2ec27d24593c3af03f9a4ca to your computer and use it in GitHub Desktop.
LZW simple implementation in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compress(uncompressed): | |
"""Compress a string to a list of output symbols.""" | |
# Build the dictionary. | |
dict_size = 256 | |
dictionary = dict((chr(i), i) for i in range(dict_size)) | |
# in Python 3: dictionary = {chr(i): i for i in range(dict_size)} | |
w = "" | |
result = [] | |
for c in uncompressed: | |
wc = w + c | |
print ( "c = ", c, ", wc = ", wc ) | |
if wc in dictionary: | |
print ( wc, " già nel dizionario" ) | |
w = wc | |
else: | |
print ( wc, " inserito nel dizionario" ) | |
result.append(dictionary[w]) | |
# Add wc to the dictionary. | |
dictionary[wc] = dict_size | |
dict_size += 1 | |
w = c | |
# print ( " dizionario = ",dictionary ) | |
# Output the code for w. | |
if w: | |
result.append(dictionary[w]) | |
print ("dictionary", dictionary) | |
return result | |
def decompress(compressed): | |
"""Decompress a list of output ks to a string.""" | |
from io import StringIO | |
# Build the dictionary. | |
dict_size = 256 | |
dictionary = dict((i, chr(i)) for i in range(dict_size)) | |
# in Python 3: dictionary = {i: chr(i) for i in range(dict_size)} | |
# use StringIO, otherwise this becomes O(N^2) | |
# due to string concatenation in a loop | |
result = StringIO() | |
w = chr(compressed.pop(0)) | |
result.write(w) | |
for k in compressed: | |
if k in dictionary: | |
entry = dictionary[k] | |
elif k == dict_size: | |
entry = w + w[0] | |
else: | |
raise ValueError('Bad compressed k: %s' % k) | |
result.write(entry) | |
# Add w+entry[0] to the dictionary. | |
dictionary[dict_size] = w + entry[0] | |
dict_size += 1 | |
w = entry | |
# print ("dictionary", dictionary) | |
return result.getvalue() | |
# How to use: | |
compressed = compress('ABBBCAB') | |
print (compressed) | |
decompressed = decompress(compressed) | |
print (decompressed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment