-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLZW.py
More file actions
40 lines (32 loc) · 1008 Bytes
/
LZW.py
File metadata and controls
40 lines (32 loc) · 1008 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from io import StringIO
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
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, dictionary
def decompress(compressed, dictionary):
output = ""
for k in compressed:
output = output + get_key(k, dictionary)
return output
def get_key(val, dictionary):
for key, value in dictionary.items():
if val == value:
return key