Medium: Interview Core · Problem 26 of 82

Caesar Cipher

MediumStringsPython

A Caesar cipher replaces each letter by the letter shift places later in the alphabet, wrapping from z back to a. Write caesar(text, shift) that returns the encoded text.

  • Upper-case letters stay upper case and lower-case letters stay lower case.
  • Characters that are not English letters (spaces, digits, punctuation) are left unchanged.
  • shift can be negative, zero or larger than 26.

Understand the problem

Work out the arithmetic of wrapping.

What does ord("c") - ord("a") give? (The position of c in the alphabet, counting a as 0.)

ord gives the character code. Subtracting the code of a gives the position 0 to 25 inside the alphabet: a is 0, b is 1, c is 2.

What is (25 + 3) % 26? (The letter z is position 25. Shift it by 3.)

28 % 26 = 2, which is the letter c. The modulo operator is exactly the "wrap around" operation.

What is (0 - 1) % 26 in Python?

Python's % never gives a negative result for a positive divisor, so shifting a back by one lands on position 25, the letter z. This is why negative shifts work without any extra code.

Write the solution

Handle both cases of letters and leave the rest alone.

def caesar(text, shift):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

How can you turn a letter into a number from 0 to 25, move it, and turn it back? What differs between upper and lower case?

Hint 2: the shape of the answer

For each character: if it is a lower-case letter, use the base ord("a"); if upper-case, use ord("A"); otherwise keep it. New letter = chr((ord(ch) - base + shift) % 26 + base).

Reflect

Solution

def caesar(text, shift):
    result = []
    for ch in text:
        if "a" <= ch <= "z":
            base = ord("a")
        elif "A" <= ch <= "Z":
            base = ord("A")
        else:
            result.append(ch)
            continue
        result.append(chr((ord(ch) - base + shift) % 26 + base))
    return "".join(result)

Another way: translate with a table

import string

def caesar(text, shift):
    shift %= 26
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    table = str.maketrans(lower + upper,
                          lower[shift:] + lower[:shift] + upper[shift:] + upper[:shift])
    return text.translate(table)

What this tests: ord and chr, the modulo operator for wrap-around, comparing characters, and building a string from pieces.

Why "a" <= ch <= "z" and not ch.isalpha(): isalpha() is also true for letters such as é or ß, which are not in the 26-letter alphabet. The task says English letters only.

Why the base: subtracting ord("a") turns a letter into 0 to 25, so % 26 can wrap it. Adding the base back gives the letter again.

Cost: O(n). The translation table version does the same work in the C code of str.translate.

What an interviewer might ask next: How would you decode a message when you do not know the shift? (Try all 26 and look for words, or count the most common letter.)