Caesar Cipher

  • + 0 comments

    python solution using string library and a dictionary:

    def caesarCipher(s, k):
    
        alpha_l = string.ascii_lowercase
        num_letters = len(alpha_l)
        alpha_u = string.ascii_uppercase
    
        rotated = dict()
        for i, letter in enumerate(alpha_l):
            rotated[letter] = alpha_l[(i + k) % num_letters]
            rotated[letter.upper()] = alpha_u[(i + k) % num_letters]
        
        cipher = ""
        for l in s:
            if l in rotated.keys():
                cipher += rotated.get(l)
            else:
                cipher += l
        
        return cipher