Created
September 15, 2015 05:33
-
-
Save rishi93/b40b9babfe42fc48f389 to your computer and use it in GitHub Desktop.
Lempel Ziv Welch
This file contains hidden or 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
def encode(string): | |
result = [] | |
for c in string: | |
result.append(ord(c)) | |
return result | |
def compress(string): | |
dictionary = {chr(i):i for i in range(97,123)} | |
last = 256 | |
result = [] | |
p = "" | |
for c in string: | |
pc = p + c | |
if pc in dictionary: | |
p = pc | |
else: | |
result.append(dictionary[p]) | |
dictionary[pc] = last | |
last += 1 | |
p = c | |
if p: | |
result.append(dictionary[p]) | |
return result | |
def decompress(arr): | |
dictionary = {i:chr(i) for i in range(97,123)} | |
last = 256 | |
result = [] | |
p = arr.pop(0) | |
for c in arr: | |
pc = dictionary[p] + dictionary[c][0] | |
if pc in dictionary: | |
p = pc | |
else: | |
dictionary[last] = pc | |
last += 1 | |
result.append(dictionary[p]) | |
p = c | |
if p: | |
result.append(dictionary[p]) | |
return ''.join(result) | |
data = "thisisthe" | |
print "Original data:",encode(data) | |
compressed = compress(data) | |
print "Compressed Data:",compressed | |
decompressed = decompress(compressed) | |
print "Decompressed Data:",decompressed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment