One line Vigeneré single decrypt/encrypt function with generator

TrustyTony 0 Tallied Votes 537 Views Share

I did some transformation of overcomplicated Rosetta code version

# Vigenère cipher one liner based on http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
from itertools import cycle

def vigenere(message, key, encode=True):
    return "".join(chr((((ord(k) if encode else -ord(k)) + ord(c)) % 26) + ord('A'))
                   for c,k in  zip((m.upper() for m in message if m.isalpha()), cycle(key))) 

#Demonstrating:
if __name__ =='__main__':
    text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
    key = "VIGENERECIPHER"

    encr = vigenere(text, key)
    decr = vigenere(encr, key, encode=False)

    print(text)
    print(encr)
    print(decr)