def encode(self, message): #initializing Table[0 to 255] to corresponding ASCII charaters Table = initialize(encode=True) #initializing table index and P index = 256 counter = 0 output = [] P = '' #LZW compression algorithm while counter != len(message) + 1: try: C = message[counter] except IndexError: # for the last iteration, C is empty so just return P and exit output.append(Table[P]) break if P + C in Table: P = P + C else: output.append(Table[P]) Table[P + C] = index index += 1 P = C counter += 1 #if the dictionary outgrew the word_size, re_initialize the dictionary if index > 2**self.word_size: Table = initialize(encode=True) index = 256 packed_output = BitString() packed_output.pack_numbers(output, self.word_size) return packed_output
def encode(self, message): output = [] main_dictionary = {} for i in range(256): main_dictionary[chr(i)] = i string = message[0] curr_index = 0 l = len(message) while curr_index < l - 1: symbol = message[curr_index + 1] if string + symbol in main_dictionary: string += symbol else: output.append(main_dictionary[string]) max_key = max(main_dictionary, key=main_dictionary.get) max_val = main_dictionary[max_key] if max_val == 2**16 - 1: main_dictionary = {} for i in range(256): main_dictionary[chr(i)] = i #main_dictionary[string+symbol]=0 else: main_dictionary[string + symbol] = max_val + 1 string = symbol curr_index += 1 output.append(main_dictionary[string]) bits = BitString() bits.pack_numbers(output, 16) return bits