-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimized.py
More file actions
32 lines (25 loc) · 967 Bytes
/
optimized.py
File metadata and controls
32 lines (25 loc) · 967 Bytes
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
def decode(message_file):
OVERWRITE_DUPLICATE = True
sentence = {}
steps = []
with open(message_file, "r") as file:
for line in file:
n, word = line.strip().split(" ")
n = int(n)
nKey = (n * (n + 1)) // 2
maxKey = len(steps) * (len(steps) + 1) // 2
# add more steps only when needed
while nKey >= maxKey:
steps.append(maxKey)
sentence[maxKey] = None
maxKey = len(steps) * (len(steps) + 1) // 2
# add the word to the sentence dictionary
if n in sentence and (OVERWRITE_DUPLICATE or sentence[n] is None):
sentence[n] = word
# compile the sentence dictionary into a decoded string
decoded_string = " ".join(
sentence[val] for val in steps if sentence[val] is not None
)
return decoded_string
decoded_message = decode("example.txt")
print(decoded_message)