note: the letters are there twice so when shifting a letter at the end of the alphabet i dont get a out of range error
so currently im working on a caesers cypher where you write a word and shift those letters by a certain amount of times
input = abc
output = bcd
my issue is when the code runs it prints the output letters twice
input = abc
output = bbccdd
heres my code
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def encrypt(text, shift):
cipher_text = ""
for i in text:
for letter in alphabet:
if i == letter:
index = alphabet.index(letter)
shifted_index = index + shift
shifted_letter = alphabet[shifted_index]
cipher_text += shifted_letter
print(f"The encoded word is {cipher_text}")
encrypt(text, shift)
another example
input = zulu
expected output = avmv
code output = aavvmmvv
>Solution :
Lots of work for what is essentially a one-liner:
import string
alphabet = string.ascii_lowercase
index = {ch: i for i, ch in enumerate(alphabet)}
def encrypt(txt, n):
return ''.join(alphabet[(index[c] + n) % len(alphabet)] for c in txt)
print(encrypt('spin', 5))
prints
xuns