0

I am attempting to decrypt the ciphertext "htrgti" to plaintext using this code. I keep getting "wigvix" which is not the message I should be getting.

Given the plain text (which should be a common word or phrase) and key, for every spot that said ciphertext I replaced it with plaintext, and the same for every spot that says plaintext:

def caesar(ciphertext, shift):  
    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"]  
    plaintext = ""

    for i in range(len(ciphertext)):                        
        letter = ciphertext[i]                  

        # Find the number position of the ith letter
        num_in_alphabet = alphabet.index(letter)        

        # Find the number position of the cipher by adding the shift    
        plain_num = (num_in_alphabet + shift) % len(alphabet)   

        # Find the plain letter for the cipher number you computed
        plain_letter = alphabet[plain_num]          

        # Add the cipher letter to the plaintext
        plaintext = plaintext + plain_letter            

    return plaintext
Michael Currie
  • 13,721
  • 9
  • 42
  • 58

1 Answers1

0

Your function works if you call it correctly, as hinted by @Mr.Llama, with the right shift caesar("htrgti", 11) is secret. Your function itself runs correctly. Here is a better version of your code, but it still has the problem that each .index lookup is O(alphalen). So, as a bonus, I added the implementation of the suggestion by @Two-Bit Alchemist to use str.translate.

import string
alphabet = string.ascii_lowercase
alphalen = len(alphabet)
shift = 11

def caesar(ciphertext, shift):  
    plaintext = ""
    for letter in ciphertext:
        num_in_alphabet = alphabet.index(letter)        
        plain_num = (num_in_alphabet + shift)  %  alphalen
        plain_letter = alphabet[plain_num]          
        plaintext = plaintext + plain_letter            
    return plaintext

print(caesar("htrgti", shift))
# secret

table = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
print("htrgti".translate(table))
# secret
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52