-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmetic.py
More file actions
75 lines (57 loc) · 2.23 KB
/
Copy pathArithmetic.py
File metadata and controls
75 lines (57 loc) · 2.23 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
import sys
class ArithmeticCoding:
def __init__(self, probabilities):
self.probabilities = probabilities
def compress(self, message):
low = 0.0
high = 1.0
for symbol in message:
pRange = high - low
symbol_low, symbol_high = self.probabilities[symbol]
high = low + pRange * symbol_high
low = low + pRange * symbol_low
return (low + high) / 2
def decompress(self, code, message_length):
low = 0.0
high = 1.0
decoded_message = []
for _ in range(message_length):
pRange = high - low
value = (code - low) / pRange
# print(value)
for symbol, (symbol_low, symbol_high) in self.probabilities.items():
if symbol_low <= value < symbol_high:
decoded_message.append(symbol)
high = low + pRange * symbol_high
low = low + pRange * symbol_low
break
return ''.join(decoded_message)
def main(input_file, compressed_file, decompressed_file):
with open(input_file, "r") as f:
lines = f.readlines()
probabilities = {}
message = None
for line in lines:
if "message:" in line.lower():
message = line.split(":")[1].strip()
else:
symbol, low, high = line.strip().split()
probabilities[symbol] = (float(low), float(high))
if message is None:
raise ValueError("Message not found in input file.")
ac = ArithmeticCoding(probabilities)
compressed_code = ac.compress(message)
with open(compressed_file, "w") as f:
f.write(str(compressed_code))
print(f"Compressed Succesfully")
decompressed_message = ac.decompress(compressed_code, len(message))
with open(decompressed_file, "w") as f:
f.write(decompressed_message)
print(f"Decompressed Succesfully")
if __name__ == "__main__":
argv = sys.argv[1:]
main(
argv[0] if len(argv) > 0 else "arithmetic_input.txt",
argv[1] if len(argv) > 1 else "compressed.txt",
argv[2] if len(argv) > 2 else "decompressed.txt",
)