I can't get an output with space characters

54 Views Asked by At

I have a cryptography project and want to decrypt sentences using python. I wrote this code but can't get an output, where the words have spaces between them.

def vigenere_decrypt(key: str, text: str) -> str:
    decrypted_text = ""
    encrypted_text = text.replace(" ", "")
    key_length = len(key)


    for i, char in enumerate(encrypted_text): #ex. 0 y, 1 a...
       
        key_char = key[i % key_length] # ex. key = KEY, text = MESSAGE => KEYKEYK
        shifted_char = (ord(char) - (ord(key_char))) % 26
        
        for c in text:
            if c in text == " ":
                decrypted_char = " "
            else:
                decrypted_char = chr((shifted_char) + ord('a'))
        decrypted_text += decrypted_char
    
    return decrypted_text
    raise NotImplementedError()
print(vigenere_decrypt("math", "yadl ut ahbpxu") )

I guess my for c in text block doesn't work and don't know why. I would be really happy if you could help me.

2

There are 2 best solutions below

0
On

if c in text == " " is not doing what you want. It's checking if the value of c in text, which can be either True or False, is equal to the string " ", which will never be possible, and therefore a space character will never be outputted. It almost certainly seems like the only code you need for that line is if c == " ".

0
On

Here is a solution that will preserve the spaces in your decryption routine.

def find_indices(input_string, target_char):
    indices = []
    for i, char in enumerate(input_string):
        if char == target_char:
            indices.append(i - len(indices))
    return indices

def vigenere_decrypt(key: str, text: str) -> str:
    decrypted_text = ""
    key_length = len(key)
    spaces = find_indices(text," ")
    ciphertext = text.replace(" ","")

    for i, char in enumerate(ciphertext): #ex. 0 y, 1 a...
        key_char = key[i % key_length] # ex. key = KEY, text = MESSAGE => KEYKEYK
        shifted_char = (ord(char) - (ord(key_char))) % 26

        if i in spaces:
            decrypted_text += " "
        decrypted_text += chr((shifted_char) + ord('a'))

    return decrypted_text
    raise NotImplementedError()
print(vigenere_decrypt("math", "yadl ut ahbpxu") )

This works by first identifying the indices of where spaces should occur in the stripped ciphertext. The find_indices method does this by identifying each space and calculating the corresponding index in the stripped text.

Then you can simply run your decrypt routine as before, where the shifted char of the previous iteration is used on the next iteration, but not on the spaces. In other words, the decrypt routine runs as if there were no spaces but it still injects the spaces where they should be.