Add decoding script

This commit is contained in:
2020-02-23 10:12:22 +00:00
parent f01a096b9c
commit 82d4b04fbc

View File

@@ -18,9 +18,7 @@ def find_node(nodes, target_character):
# if desired character not found, return empty list
return []
# retrieve text to encode
txt = input("Text: ")
def encode(txt):
# create list of tuples in descending order of frequency: (character, frequency)
info = Counter(txt).most_common()
# change the list into ascending order
@@ -76,5 +74,32 @@ for char in txt:
# find its path and add it to the encrypted text
output += "".join(find_node(nodes, char))
# print encrypted message
print("Encrypted message: %s" % output)
# print encoded message
print("Encoded message: %s" % output)
# return encoded message
return [output, nodes]
def decode(txt, nodes):
# string to hold decoded message
output = ""
# replicate nodes, for looping over and editing with the first part of the code
node = nodes
# for each digit
for digit in txt:
# get the node with the corresponding index
node = node[int(digit)]
# if the retrieved node isn't a tuple (i.e. it isn't a parent node)
if (not isinstance(node, tuple)):
# add the node's content to the output
output += node
# replace the retrieved node with the whole tree again, for looping over and editing with the next part of the code
node = nodes
# print decoded message
print("Decoded message: %s" % output)
# return decoded message
return output
encoding = encode(input("Text: "))
decode(encoding[0], encoding[1])