A simple pythonic algorithm to decode an unstructured, randomized text file (a simple exercise in intelligence)
Thank you for reviewing this simple bit of code that I recently submitted as part of a technical exam. The task was to decode a message from a randomized, unstructured text file containing labeled pairs (an integer and a string). The key to decoding this mysterious message is to read the last word from three consecutive layers of the data after it has been restructured as a pyramid.
[1]
[2,3]
[4,5,6]
[7,8,9,10]
...
1 top
2 of
3 secret
4 power
5 excite
6 message
7 dog
8 opposite
9 oxygen
10 whole
...
** The algorithm, when set to parameters [1,3,6], will output:
The steps taken to leverage python to execute the decodification of this message are as follows:
The file provided is a text file (.txt), comprised of two columns: an integer column (leftmost column) and a string (rightmost column). Since all columns within a .txt file are rendered as strings, we must first convert the leftmost column representing integer-based coding to...integer values; likewise, we must ensure that we preserve the corresponding code values in the rightmost column as strings. To accomplish this, we may use a combination of simple logic, nested loops, and the split().split() method to tell our function to read the left column as integers and the right column as strings values, with which we may proceed to execute the program.
The key methodology for decoding the file is to arrange it as a pyramid, where every layer of the pyramid adds another value to the end of the sequence, such that Layer 1 = [1], Layer 2 = [2,3], Layer 3 = [4,5,6], etc. Accordingly, the last value of every level on the top three levels (that is, indices 1, 3, and 6) represent three words that form the message we are trying to decode. To execute, we simply need to arrange these values into a list of lists, with each inner list representing a layer of the pyramid.
The final step is to iterate through the indices we've set as the encoded message (1,3,6) with for loop and return the corresponding strings. All there is left to do now is return the pyramid and decoded message.
After performing the function on the text file, we return a pyramid-structured list, as well as the final decoded message ("top secret message").