Python - Read two letters in table from string

Viewed 57

I'm doing a ADFGVX cipher encoder and decoder and I have a polybius square where I need to read two letters.

reversesquare = {'AA': '1', 'AD': '2', 'AF': '3', 'AG': '4', 'AV': '5', 'AX': '6',
                 'DA': '7', 'DD': '8', 'DF': '9', 'DG': '0', 'DV': 'Q', 'DX': 'W',
                 'FA': 'E', 'FD': 'R', 'FF': 'T', 'FG': 'Y', 'FV': 'U', 'FX': 'I',
                 'GA': 'O', 'GD': 'P', 'GF': 'A', 'GG': 'S', 'GV': 'D', 'GX': 'F',
                 'VA': 'G', 'VD': 'H', 'VF': 'J', 'VG': 'K', 'VV': 'L', 'VX': 'Z',
                 'XA': 'X', 'XD': 'C', 'XF': 'V', 'XG': 'B', 'XV': 'N', 'XX': 'M'}
def Decrypt_Final(sortedcipher):
    mensagemcifrada = ""
    for letter in sortedcipher:  # Esta a ler letra a letra quando devia ser 2 de uma vez
        if letter in reversesquare:
            mensagemcifrada += (reversesquare[letter])
    return mensagemcifrada

I have this function which is gonna take a string (sortedcipher) like: GXFXVVFXGDFA

I want my program to read two letters each time its loops over it like, "GX" "FX" .... and find in my reversesquare when it matches.

3 Answers

You could zip the string with an offset like this:

for a, b in zip(sortedcipher, sortedcipher[1:]):
      pair = a + b
      # pair now contains "GF", "FX" and so on..

A "one-liner", though less readable, would be following.

def Decrypt_Final(sortedcipher):
  return "".join([
    reversesquare[sortedcipher[i:i+2]]
      for i in range(0, len(sortedcipher), 2)
    ]
  )

Another option is to use list-comprehensoion:

def Decrypt_Final(sortedcipher):
    # turns the cipher into a list of strings where each element
    # contains two characters from the string
    letters = (sortedcipher[i:i+2] for i in range(0, len(sortedcipher), 2))
    return [reversesquare[letter] for letter in letters]
Related