MCPcopy
hub / github.com/TheAlgorithms/Python / compress_data

Function compress_data

data_compression/lempel_ziv.py:44–71  ·  view source on GitHub ↗

Compresses given data_bits using Lempel-Ziv-Welch compression algorithm and returns the result as a string

(data_bits: str)

Source from the content-addressed store, hash-verified

42
43
44def compress_data(data_bits: str) -> str:
45 """
46 Compresses given data_bits using Lempel-Ziv-Welch compression algorithm
47 and returns the result as a string
48 """
49 lexicon = {"0": "0", "1": "1"}
50 result, curr_string = "", ""
51 index = len(lexicon)
52
53 for i in range(len(data_bits)):
54 curr_string += data_bits[i]
55 if curr_string not in lexicon:
56 continue
57
58 last_match_id = lexicon[curr_string]
59 result += last_match_id
60 add_key_to_lexicon(lexicon, curr_string, index, last_match_id)
61 index += 1
62 curr_string = ""
63
64 while curr_string != "" and curr_string not in lexicon:
65 curr_string += "0"
66
67 if curr_string != "":
68 last_match_id = lexicon[curr_string]
69 result += last_match_id
70
71 return result
72
73
74def add_file_length(source_path: str, compressed: str) -> str:

Callers 1

compressFunction · 0.85

Calls 1

add_key_to_lexiconFunction · 0.85

Tested by

no test coverage detected