Положение в цикле for дает разные результаты

Я пытаюсь создать простой шифр на Python с функциями кодирования и кодирования.

Он берет слово от пользователя, применяет указанный номер сдвига и сдвигает каждую букву вперед на это значение индекса в списке алфавита.

Так:

Text = "hello"  
  
Shift = "5"

Даст: "mjqqt"

Декодирование превратит «mjqqt» обратно в «привет».

В зависимости от того, где находится мой оператор if, я получаю либо «холво», либо «привет», и меня беспокоит, что я неправильно понимаю порядок операций.

Первый код ниже с оператором if внутри цикла for даст мне ответ «holvo», когда он попытается декодировать «mjjqt»

#Provide alphabet list and starting input variables

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"))

#Combine the encrypt and decrypt functions into a single function called caesar(). 

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  for letter in start_text:
    position = alphabet.index(letter)
    if cipher_direction == "decode":
          shift_amount *= -1
    new_position = position + shift_amount
    end_text += alphabet[new_position]
    
  print(f"Here's the {direction}d result: {end_text}")

caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

Приведенный ниже оператор if вне цикла for даст мне правильный ответ «привет», когда он попытается декодировать «mjjqt».

#Provide alphabet list and starting input variables

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"))

#Combine the encrypt and decrypt functions into a single function called caesar().

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
      shift_amount *= -1
  for letter in start_text:
    position = alphabet.index(letter)
    new_position = position + shift_amount
    end_text += alphabet[new_position]
  print(f"Here's the {direction}d result: {end_text}")

caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

🤔 А знаете ли вы, что...
Python был создан Гвидо ван Россумом и впервые выпущен в 1991 году.


53
1

Ответ:

Решено

Причина, по которой первый пример не работает, заключается в том, что на каждой итерации цикла величина сдвига меняется.

Когда он находится перед циклом, он переворачивается только один раз, поэтому вы получаете ожидаемый результат.

# Iteration 1
shift_amount = -5

# Iteration 2
shift_amount =  5

# Iteration 3
shift_amount = -5
...