def lz78_compress(data: bytes) -> list: dictionary = {b'': 0} next_index = 1 result = [] current_phrase = b'' for char in data: new_phrase = current_phrase + char.to_bytes(1, 'big') if new_phrase in dictionary: current_phrase = new_phrase else: result.append((dictionary[current_phrase], char)) dictionary[new_phrase] = next_index next_index += 1 current_phrase = b'' if current_phrase: result.append((dictionary[current_phrase], 0)) return result def compress(input_file, output_file): with open(input_file, 'rb') as f: original_data = f.read() compressed_data = lz78_compress(original_data) len_compressed_data = len(compressed_data) with open(output_file, 'wb') as out: out.write(len_compressed_data.to_bytes(2, 'big')) for index, char in compressed_data: out.write(index.to_bytes(2, 'big')) out.write(char.to_bytes(1, 'big')) if __name__ == '__main__': compress('Q7B.bmp', 'Q7B.bin')