Add decoding script
This commit is contained in:
@@ -18,9 +18,7 @@ def find_node(nodes, target_character):
|
|||||||
# if desired character not found, return empty list
|
# if desired character not found, return empty list
|
||||||
return []
|
return []
|
||||||
|
|
||||||
# retrieve text to encode
|
def encode(txt):
|
||||||
txt = input("Text: ")
|
|
||||||
|
|
||||||
# create list of tuples in descending order of frequency: (character, frequency)
|
# create list of tuples in descending order of frequency: (character, frequency)
|
||||||
info = Counter(txt).most_common()
|
info = Counter(txt).most_common()
|
||||||
# change the list into ascending order
|
# change the list into ascending order
|
||||||
@@ -76,5 +74,32 @@ for char in txt:
|
|||||||
# find its path and add it to the encrypted text
|
# find its path and add it to the encrypted text
|
||||||
output += "".join(find_node(nodes, char))
|
output += "".join(find_node(nodes, char))
|
||||||
|
|
||||||
# print encrypted message
|
# print encoded message
|
||||||
print("Encrypted message: %s" % output)
|
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])
|
||||||
|
|||||||
Reference in New Issue
Block a user