Vigenère Cipher Tool

Lab Python Advanced 30 points

Read a mode (encrypt/decrypt), a keyword and a message. Apply the Vigenère cipher to letters only (keep case; the key advances only on letters), leaving other characters as they are.

Input

Three lines: mode, key, message.

Output

The result.

Example

Input

encrypt
lemon
Attack at dawn!

Output

Lxfopv ef rnhr!
Sample input available Sample output available
Editor
Python

Hints

Each letter is shifted by the matching key letter (a=0, b=1, ...).

Decryption uses the same code with a negative shift.

Solution explanation

Writing one function with a direction parameter avoids duplicating the encrypt and decrypt logic.

Show solution
def vigenere(text, key, sign):
    out = []
    k = 0
    for ch in text:
        if ch.isalpha():
            base = ord("A") if ch.isupper() else ord("a")
            shift = ord(key[k % len(key)].lower()) - ord("a")
            out.append(chr((ord(ch) - base + sign * shift) % 26 + base))
            k += 1
        else:
            out.append(ch)
    return "".join(out)


mode = input()
key = input()
message = input()
print(vigenere(message, key, 1 if mode == "encrypt" else -1))
Output
Answer
HOME LEARN COMMUNITY DASHBOARD