pythonlistcaesar-cipher

How to match elements from input to list


I'm currently working on a Caesar cipher program, and I basically typed up a list of the alphabets: alphabet = ['a','b','c','d',...]

Then asked the user for a word to encrypt, text = input('Enter your message') and the shift amount, I figured I could set an empty string variable and then loop through (for loop) each letter to shift it.

But this is where I got stuck, how will I shift each letter in the input by the shift amount using the list?

I tried to loop through the input using the indexes of the list alphabet, but since had no idea what I was doing it didn't work.


Solution

  • Here's a generic implementation of the caesar-cipher, that should work for any shift amount, and any charset.

    Feel free to get rid of the type hinting if you feel it hinders readability. I personally would prefer to have it though.

    import string
    from typing import Hashable, Iterable, Sequence, TypeVar
    
    T = Hashable
    def caesar_ciper(message: Iterable[T], k: int, charset: Sequence[T] = string.ascii_lowercase) -> Iterable[T]:
        n = len(charset)
        char_idx = dict(zip(charset, range(n)))
        shift = lambda x: charset[(char_idx[x] + k) % n]
        return map(shift, message)
        
    message = 'abcxyz' # read from user
    k = 3 # read from user
    
    encoded = ''.join(caesar_ciper(message, k))
    assert encoded == 'defabc'