-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathlzw.py
69 lines (62 loc) · 1.79 KB
/
lzw.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
* Execution: python lzw.py - < input.txt (compress)
* Execution: python lzw.py + < input.txt (expand)
* Data files: https://algs4.cs.princeton.edu/55compression/abraLZW.txt
* https://algs4.cs.princeton.edu/55compression/ababLZW.txt
*
* % python lzw.py - < abraLZW.txt | python lzw.py +
* ABRACADBRACRAACRA
*
"""
from algs4.binarystdin import BinaryStdin
from algs4.binarystdout import BinaryStdout
from algs4.tst import TST
class LZW:
R = 256
L = 4096
W = 12
@classmethod
def compress(cls):
input = BinaryStdin.read_str()
st = TST()
for i in range(cls.R):
st.put(chr(i), i)
code = cls.R+1
while len(input) > 0:
s = st.long_prefix_of(input)
BinaryStdout.write_bits(st.get(s), cls.W)
t = len(s)
if t < len(input) and code < cls.L:
st.put(input[:t+1], code)
code += 1
input = input[t:]
BinaryStdout.write_bits(cls.R, cls.W)
BinaryStdout.close()
@classmethod
def expand(cls):
st = ["" for _ in range(cls.L)]
for i in range(cls.R):
st[i] = chr(i)
st[i] = " "
i += 1
codeword = BinaryStdin.read_int_r(cls.W)
val = st[codeword]
while True:
BinaryStdout.write_str(val)
codeword = BinaryStdin.read_int_r(cls.W)
if codeword == cls.R:
break
s = st[codeword]
if i == codeword:
s = val + val[0]
if i < cls.L:
st[i] = val + s[0]
i += 1
val = s
BinaryStdout.close()
if __name__ == '__main__':
import sys
if sys.argv[1] == "-":
LZW.compress()
else:
LZW.expand()