Skip to content

Commit

Permalink
add lzw
Browse files Browse the repository at this point in the history
  • Loading branch information
shellfly committed Feb 8, 2020
1 parent 2121281 commit 2506a84
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
5 changes: 5 additions & 0 deletions algs4/binarystdout.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ def write_bit(cls, bit):
if cls.n == 8:
cls.clear_buffer()

@classmethod
def write_str(cls, s):
for i in range(len(s)):
cls.write_byte(ord(s[i]))

@classmethod
def clear_buffer(cls):
if cls.n == 0:
Expand Down
76 changes: 76 additions & 0 deletions algs4/lzw.py
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()

0 comments on commit 2506a84

Please sign in to comment.