SHARE
TWEET

Untitled

a guest Feb 21st, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Compressor(object):
  2.     def __init__(self, window_size, max_code_length):
  3.         self.window_size = window_size
  4.         self.max_code_length = max_code_length
  5.  
  6.     def find_match(self):
  7.         max_len = 0
  8.         max_offset = 0
  9.         j = 0
  10.         for i in range(self.window_size):
  11.             if self.lookahead[0] == self.window[i]:
  12.                 j = 1
  13.                 while j < len(self.lookahead) and (i + j) < len(self.window) and self.lookahead[j] == self.window[i + j]:
  14.                     if j > self.max_code_length:
  15.                         break
  16.                     j += 1
  17.                 if j > max_len:
  18.                     max_len = j
  19.                     max_offset = i
  20.         return max_offset, max_len
  21.  
  22.     def compress(self, string):
  23.         self.lookahead = string[:self.max_code_length]
  24.         self.window = ' ' * self.window_size
  25.         output = []
  26.         n = 0
  27.         offset, length = self.find_match()
  28.         while n < len(string):
  29.             if length <= 2:
  30.                 output.append(string[n])
  31.                 length = 1
  32.             else:
  33.                 output.append((offset, length))
  34.  
  35.             self.window = self.window[length:] + string[n:n + length]
  36.             self.lookahead = self.lookahead[length:] + string[n + self.max_code_length:n + self.max_code_length + length]
  37.             if len(self.lookahead) == 0:
  38.                 break
  39.  
  40.             n += length
  41.  
  42.             offset, length = self.find_match()
  43.  
  44.         return output
  45.  
  46.     def decompress(self, comp):
  47.         result = ' ' * self.window_size
  48.         for c in comp:
  49.             if isinstance(c, str):
  50.                 result += c
  51.             else:
  52.                 offset, length = c
  53.                 base = len(result) - self.window_size + offset
  54.                 result += result[base:base + length]
  55.         return result[self.window_size:]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top