Anonymous user
LZW compression: Difference between revisions
→{{header|Python}}
No edit summary |
|||
Line 242:
=={{header|Python}}==
<python>
from collections import deque
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
dictionary =
▲ w = ''
▲ result = []
for c in uncompressed:
wc = w + c
Line 262 ⟶ 263:
dictionary[wc] = dict_size
dict_size += 1
w = c
# Output the code for w.
if w:
result
return result
def decompress(compressed):
"""Decompress a list of output ks to a string."""
# Build the dictionary.
dict_size = 256
dictionary = {}
for i in
dictionary[chr(i)] = chr(i)
w = result = compressed.
for k in compressed:
if k in dictionary:
Line 287 ⟶ 289:
raise ValueError, 'Bad compressed k: %s' % k
result += entry
# Add w+entry[0] to the dictionary.
dictionary[dict_size] = w + entry[0]
dict_size += 1
w = entry
return result
How to use:▼
▲# How to use:
print compressed
decompressed = decompress(compressed)
print decompressed
</python>
Output:
<python>
['T', 'O', 'B', 'E', 'O', 'R', 'N', 'O', 'T', 256, 258, 260, 265, 259, 261, 'O', 'T']
TOBEORNOTTOBEORTOBEORNOT
</python>
|