-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
""" | ||
* 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 | ||
* | ||
* Compress or expand binary input from standard input using LZW. | ||
* | ||
* WARNING: STARTING WITH ORACLE JAVA 6, UPDATE 7 the SUBSTRING | ||
* METHOD TAKES TIME AND SPACE LINEAR IN THE SIZE OF THE EXTRACTED | ||
* SUBSTRING (INSTEAD OF CONSTANT SPACE AND TIME AS IN EARLIER | ||
* IMPLEMENTATIONS). | ||
* | ||
* See <a href = "http://java-performance.info/changes-to-string-java-1-7-0_06/">this article</a> | ||
* for more details. | ||
* | ||
""" | ||
|
||
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() |