RosettaCodeData/Task/LZW-compression/Python/lzw-compression.py

64 lines
1.6 KiB
Python
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
2020-02-17 23:21:07 -08:00
dictionary = dict((chr(i), i) for i in range(dict_size))
2016-12-05 22:15:40 +01:00
# in Python 3: dictionary = {chr(i): i for i in range(dict_size)}
2013-04-10 21:29:02 -07:00
w = ""
result = []
for c in uncompressed:
wc = w + c
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
# Add wc to the dictionary.
dictionary[wc] = dict_size
dict_size += 1
w = c
# Output the code for w.
if w:
result.append(dictionary[w])
return result
def decompress(compressed):
"""Decompress a list of output ks to a string."""
2020-02-17 23:21:07 -08:00
from io import StringIO
2013-04-10 21:29:02 -07:00
# Build the dictionary.
dict_size = 256
2020-02-17 23:21:07 -08:00
dictionary = dict((i, chr(i)) for i in range(dict_size))
2017-09-23 10:01:46 +02:00
# in Python 3: dictionary = {i: chr(i) for i in range(dict_size)}
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
# use StringIO, otherwise this becomes O(N^2)
# due to string concatenation in a loop
result = StringIO()
2017-09-23 10:01:46 +02:00
w = chr(compressed.pop(0))
2015-02-20 00:35:01 -05:00
result.write(w)
2013-04-10 21:29:02 -07:00
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)
2015-02-20 00:35:01 -05:00
result.write(entry)
2013-04-10 21:29:02 -07:00
# Add w+entry[0] to the dictionary.
dictionary[dict_size] = w + entry[0]
dict_size += 1
w = entry
2015-02-20 00:35:01 -05:00
return result.getvalue()
2013-04-10 21:29:02 -07:00
# How to use:
compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)