gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
шифр цезаря на python\ с помощью модульной арифметики
- User
шифр цезаря на python\ с помощью модульной арифметики
- Assistant
Код для шифра Цезаря на языке Python с использованием модульной арифметики будет выглядеть следующим образом:
def encrypt(text, shift): encrypted_text = "" for char in text: if char.isalpha(): ascii_offset = 65 if char.isupper() else 97 encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset) encrypted_text += encrypted_char else: encrypted_text += char return encrypted_text def decrypt(encrypted_text, shift): decrypted_text = "" for char in encrypted_text: if char.isalpha(): ascii_offset = 65 if char.isupper() else 97 decrypted_char = chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset) decrypted_text += decrypted_char else: decrypted_text += char return decrypted_text # Пример использования: text = "Hello, World!" shift = 3 encrypted_text = encrypt(text, shift) print("Encrypted text:", encrypted_text) decrypted_text = decrypt(encrypted_text, shift) print("Decrypted text:", decrypted_text)