Why won't this recursive caesar cipher algorithm work?

75 Views Asked by At
def encrypt(plaintext, key):
    if key == 0:
        ciphertext = plaintext
        return ciphertext

    key %= 26
    ciphertext = ""
    for letter in plaintext:
        if letter.isalpha():
            if letter.isupper():
                new_letter = chr((ord(letter) - 65 + key) % 26 + 65)
            else:
                new_letter = chr((ord(letter) - 97 + key) % 26 + 97)
            ciphertext += new_letter
        else:
            ciphertext += letter

    return encrypt(ciphertext, key - 1)

If I input "hello" and the key is 2, then I should get "jgnnq" but I get "khoor". The program only wirks if the key is 1. Does anyon know why this happens and how to fix it?

1

There are 1 best solutions below

1
dragondip On

Because you replace the value when the recursive iterates

def encrypt(plaintext, key):
    if key == 0:
        ciphertext = plaintext
        return ciphertext

    key %= 26
    print(key)
    ciphertext = ""
    for letter in plaintext:
        if letter.isalpha():
            if letter.isupper():
                new_letter = chr((ord(letter) - 65 + key) % 26 + 65)
            else:
                new_letter = chr((ord(letter) - 97 + key) % 26 + 97)

            ciphertext += new_letter
        else:
            ciphertext += letter
    print(ciphertext)

    return encrypt(ciphertext, key - 1)

encrypt("hello", 2)

Output:

2
jgnnq
1
khoor

So if you want jgnnq. Why you create recursive?

Edited under your comment:

def encrypt(plaintext, key, i = 0, ciphertext=''):
    k = key
    if key == 0:
        ciphertext = plaintext
        return ciphertext

    key %= 26
    letter = plaintext[i]
    if letter.isalpha():
        if letter.isupper():
            new_letter = chr((ord(letter) - 65 + key) % 26 + 65)
        else:
            new_letter = chr((ord(letter) - 97 + key) % 26 + 97)

        ciphertext += new_letter
    else:
        ciphertext += letter
    i+=1
    if len(ciphertext) == len(plaintext):
        return ciphertext
    return encrypt(plaintext, k, i, ciphertext)

encrypt("hello", 2)

Output:

'jgnnq'