Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for loop result is printed twice

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading