Skip to content

Instantly share code, notes, and snippets.

@nboubakr
Created December 30, 2014 23:15
Show Gist options
  • Save nboubakr/905e98342174a7e47bed to your computer and use it in GitHub Desktop.
Save nboubakr/905e98342174a7e47bed to your computer and use it in GitHub Desktop.
Lampel-Ziv 78 (LZ78) implementation in Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Lampel-Ziv 78 (LZ78)
# Théorie de l'information et du codage
# Etudiant: Boubakr NOUR <n.boubakr@gmail.com>
# Universite Djilali Liabes (UDL) de Sidi Bel Abbes
def compress(data):
dictionary, word = {0: ''}, 0
dynamic_dictionary = lambda dictionary, key: dictionary.get(key) or dictionary.__setitem__(key,
len(dictionary)) or 0
return [token for char in data for token in [(word, char)] for word in [dynamic_dictionary(dictionary, token)] if
not word] + [(word, '')]
def decompress(data):
dictionary, j = {0: ''}, ''.join
dynamic_dictionary = lambda dictionary, value: dictionary.__setitem__(len(dictionary), value) or value
return j([dynamic_dictionary(dictionary, dictionary[codeword] + char) for (codeword, char) in data])
if __name__ == '__main__':
data = "ABBCBCABABCAABCAAB"
compress_data = compress(data)
decompress_data = decompress(compress_data)
print 'DATA:', data
print 'COMPRESSING:', compress_data
print 'DECOMPRESSING:', decompress_data
@rajarshi-ch
Copy link

I get this error while trying to run this..

Traceback (most recent call last):
  File "LZ88.py", line 17, in <module>
    compress_data = compress(data)
  File "LZ88.py", line 6, in compress
    return [token for char in data for token in [(word, char)] for word in [dynamic_dictionary(dictionary, token)] if not word] + [(word, '')]
  File "LZ88.py", line 6, in <listcomp>
    return [token for char in data for token in [(word, char)] for word in [dynamic_dictionary(dictionary, token)] if not word] + [(word, '')]
UnboundLocalError: local variable 'word' referenced before assignment

Can you help?

@donCESAR12345
Copy link

Use python2 instead of python3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment