Jump to content

LZW compression: Difference between revisions

No edit summary
Line 242:
=={{header|Python}}==
 
<python>def compress(uncompressed):
from collections import deque
 
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
 
# Build the dictionary.
dict_size = 256
dictionary = {}dict((chr(i), chr(i)) for i in xrange(dict_size))
 
for i in range(dict_size):
w = ''""
dictionary[chr(i)] = chr(i)
result = []deque()
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 += [char for char in .extend(w])
return result
 
 
def decompress(compressed):
"""Decompress a list of output ks to a string."""
 
# Build the dictionary.
dict_size = 256
dictionary = {}
for i in rangexrange(dict_size):
dictionary[chr(i)] = chr(i)
 
w = result = compressed.poppopleft(0)
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</python>
 
How to use:
 
# How to use:
<python>compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print compressed
decompressed = decompress(compressed)
print decompressed</python>
</python>
 
Output:
<python>
['T', 'O', 'B', 'E', 'O', 'R', 'N', 'O', 'T', 256, 258, 260, 265, 259, 261, 'O', 'T']
TOBEORNOTTOBEORTOBEORNOT
</python>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.