forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelta_encoding.py
More file actions
77 lines (57 loc) · 1.76 KB
/
delta_encoding.py
File metadata and controls
77 lines (57 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Delta Encoding
--------------
Delta encoding is a lossless data compression method that stores the difference
(delta) between sequential values instead of the absolute values themselves.
For example:
Input: [100, 103, 105, 108]
Output: [100, 3, 2, 3]
The first element is stored as-is; each subsequent value is replaced
by the difference from its predecessor.
This is useful for compressing data that changes gradually, such as
sensor readings, time series data, or pixel values in images.
Reference:
https://en.wikipedia.org/wiki/Delta_encoding
"""
def delta_encode(data: list[int]) -> list[int]:
"""
Encodes a list of integers using delta encoding.
Args:
data (list[int]): A list of integers.
Returns:
list[int]: Delta-encoded list.
Example:
>>> delta_encode([100, 103, 105, 108])
[100, 3, 2, 3]
"""
if not data:
return []
deltas = [data[0]]
for i in range(1, len(data)):
deltas.append(data[i] - data[i - 1])
return deltas
def delta_decode(encoded: list[int]) -> list[int]:
"""
Decodes a delta-encoded list back to the original sequence.
Args:
encoded (list[int]): Delta-encoded list.
Returns:
list[int]: Decoded list of integers.
Example:
>>> delta_decode([100, 3, 2, 3])
[100, 103, 105, 108]
"""
if not encoded:
return []
decoded = [encoded[0]]
for i in range(1, len(encoded)):
decoded.append(decoded[-1] + encoded[i])
return decoded
if __name__ == "__main__":
# Example run
data = [100, 103, 105, 108]
encoded = delta_encode(data)
decoded = delta_decode(encoded)
print(f"Original data: {data}")
print(f"Delta Encoded: {encoded}")
print(f"Delta Decoded: {decoded}")