Editor

Vigenere Cipher

#311 · Codes and ciphers · Intermediate · 70 XP · about 14 min

A Caesar cipher shifts every letter by the same amount, which makes it easy to break. The Vigenere cipher shifts each letter by a different amount, taken from a keyword: key letter A shifts by 0, B by 1, C by 2, and so on up to Z, which shifts by 25. The keyword is repeated as many times as needed.

Write vigenere(text, key, decrypt=False) that returns the encrypted text, or the decrypted text when decrypt is True. The rules:

  • encrypting moves each letter forward through the alphabet by the shift of its key letter, wrapping from Z back to A; decrypting moves it backward by the same amount, wrapping from A to Z;
  • only the letters A to Z are changed, and each keeps its case; every other character (spaces, digits, punctuation) is copied as it is;
  • the key moves on to its next letter only after a letter of the text: other characters do not use up a key letter;
  • the key contains only letters, in upper or lower case, and a gives the same shift as A.

Examples

vigenere("MEET ME AT NOON", "CODE")                # returns 'OSHX OS DX PCRR'
vigenere("OSHX OS DX PCRR", "CODE", decrypt=True)  # returns 'MEET ME AT NOON'
vigenere("Bring 3 apples.", "pie")                 # returns 'Qzmco 3 eexpta.'

In the first example the key letters line up with the letters of the message as C O D E, C O, D E, C O D E: M shifted by 2 (C) is O, the first E shifted by 14 (O) is S, and so on. The spaces do not use up key letters.

Constraints

  • text has 0 to 20,000 characters.
  • key has 1 to 100 letters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.