Skip to content
Advertisement

I’m having trouble writing the ADFGVX cipher in python

First of all, if anyone doesn’t know how the ADFGVX Cipher works, Here is a video on it:

https://www.youtube.com/watch?v=T0xfKiU9Rr4&t=11s

Assuming you now know how the cipher works, let’s look at my problem now:

First, we need to create the Polybius Square. I did this by creating a table:

table = 
["THEMAN",
"DLORIB",
"CFGHJK",
"PQRSUV",
"WXYZ12",
"345678"]

Next, we need to create a dictionary containing the coordinates:

coordinatesdict={}

We can create a loop to add the coordinates to the dictionary.

for string in table:
    for letter in string:
        coordinatesdict[letter] = [string.index(letter), table.index(string)]

When I printed the dictionary, I was expecting this:

{T:[0,0],H:[1,0],E:[2,0].....}
#And so on and so forth.

What I got instead utterly baffled me:

{'T': [0, 0], 'H': [3, 2], 'E': [2, 0], 'M': [3, 0], 'A': [4, 0], 'N': [5, 0], 'D': [0, 1], 'L': [1, 1], 'O': [2, 1], 'R': [2, 3], 'I': [4, 1], 'B': [5, 1], 'C': [0, 2], 'F': [1, 2], 'G': [2, 2], 'J': [4, 2], 'K': [5, 2], 'P': [0, 3], 'Q': [1, 3], 'S': [3, 3], 'U': [4, 3], 'V': [5, 3], 'W': [0, 4], 'X': [1, 4], 'Y': [2, 4], 'Z': [3, 4], '1': [4, 4], '2': [5, 4], '3': [0, 5], '4': [1, 5], '5': [2, 5], '6': [3, 5], '7': [4, 5], '8': [5, 5]}

The craziness did not stop there. I debugged the loop and changed it to this:

for string in table:
    for letter in string:
        print(letter)
        print([string.index(letter), table.index(string)])

Here’s what I got after running the loop:

T [0, 0] H [1, 0] E [2, 0] M [3, 0] A [4, 0] N [5, 0] D [0, 1] L [1, 1] O [2, 1] R [3, 1] I [4, 1] B [5, 1] C [0, 2] F [1, 2] G [2, 2] H [3, 2] J [4, 2] K [5, 2] P [0, 3] Q [1, 3] R [2, 3] S [3, 3] U [4, 3] V [5, 3] W [0, 4] X [1, 4] Y [2, 4] Z [3, 4] 1 [4, 4] 2 [5, 4] 3 [0, 5] 4 [1, 5] 5 [2, 5] 6 [3, 5] 7 [4, 5] 8 [5, 5]

Apparently, When I print them out individually, they are correct, Yet when I plug them into a dictionary, everything goes wrong. Is there an explanation for this? If so, Is there a way to fix this?

Advertisement

Answer

First of all I haven’t looked at ADFGVX Cipher because I think it is more of a python problem that you are facing here.
The problem here is that table contains 2 strings that have "H" in them namely "THEMAN" and "CFGHJK"
The way you have written your code it is saying coordinatesdict to update the value corresponding to key "H" to a new value whenever it sees one.
Since your code sees a new "H" at position (2,3) it updates the value of "H" to be coordinatesdict['H']=[3,2] and hence you see your unexpected result.

So in a nutshell you are using a wrong data structure (i.e. dictionary) for your problem. You can try defaultdict or any other data structure for your problem.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement