Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Caesar function wrong output

I am following 100 days of code and I'm having trouble understanding why this function isn't working properly.

alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","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","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","r","s","t","u","v","w","x","y","z"]

direction = input("Type 'encode' for Encode type 'decode' for Decode")
text = input("Type your message: \n").lower()
shift = int(input("Type the shift number: \n"))

def cesar(input_text,shift_ammount,which_direction):
    word = ""
    for letter in input_text:
        position = alphabet.index(letter)
        if which_direction == "decode":
            shift_ammount *= -1
        new_position = position + shift_ammount
        word += alphabet[new_position]
    print(f"the {which_direction}d text is {word}")

cesar(input_text=text,shift_ammount=shift,which_direction=direction)

Let's say I'm trying to decode the string "bcd". It returns "adc" instead of "abc". For some reason, it adds instead of subtracting to the second position and returns the wrong value. Any help would be welcomed!

like image 614
Selotejp Avatar asked Mar 01 '23 20:03

Selotejp


1 Answers

The problem is the line:

shift_ammount *= -1

This line is inside the for-loop which means that the shift_ammount will change the value in each iteration. Place this part of the code outside the for-loop to get the correct result.

Updated code:

def cesar(input_text, shift_ammount, which_direction):
    word = ""
    if which_direction == "decode":
        shift_ammount *= -1
    for letter in input_text:
        position = alphabet.index(letter)
        new_position = position + shift_ammount
        word += alphabet[new_position]
    print(f"the {which_direction}d text is {word}")
like image 54
Shaido Avatar answered Mar 15 '23 06:03

Shaido