Caesar Cipher

  • + 0 comments

    Python solution:

    def caesarCipher(string: str, k: int) -> str:
        if k == 0:
            return string
        vocab = "abcdefghijklmnopqrstuvwxyz"
        cipher = []
        for char in string:
            if not char.isalpha():
                cipher.append(char)
            else:
                idx = vocab.index(char.lower())   # index of character
                new_char = vocab[(idx + k) % len(vocab)]    # shift index
                # capitalise if required:
                new_char = new_char.upper() if char.isupper() else new_char 
                cipher.append(new_char)
        return "".join(cipher)