Не корректно работает Шифр с использованием букв
Делаю шифр с помощью букв из строчки ввода. Для текста, который состоит из одного слова шифрует верно, но если их несколько или встречаются большие буквы - начинаются не точности. Как возможно исправить?!
if len(sys.argv) != 2:
sys.exit("Ошибка")
key = (sys.argv[1])
for k in key:
if not k.isalpha():
sys.exit("Ошибка")
index = 0
chiper = ""
text = input ("Исходный: ")
for c in text:
if c in string.ascii_lowercase and string.ascii_uppercase:
offset = ord(key[index]) - ord('a')
encrypted_c = chr((ord(c) - ord('a') + offset) %26 + ord('a'))
chiper = chiper + encrypted_c
index = (index + 1) % len(key)
else:
chiper = chiper + c
print ("Шифр: " + chiper)
Ответы (1 шт):
Автор решения: n1tr0xs
→ Ссылка
Из-за того, что символы нижнего и верхнего регистра располагаются не подряд приходится проверять какого регистра мы шифруем.
Вот так нужно изменить цикл for чтобы работало как вы хотите:
for c in text:
if c not in (string.ascii_lowercase+string.ascii_uppercase):
chiper += c
continue
if key[index].islower():
offset = ord(key[index]) - ord('a')
else:
offset = ord(key[index]) - ord('A')
if c.islower():
encrypted_c = chr((ord(c) - ord('a') + offset) %26 + ord('a'))
else:
encrypted_c = chr((ord(c) - ord('A') + offset) %26 + ord('A'))
chiper += encrypted_c
index = (index + 1) % len(key)
И можно немного сократить код вот так:
for c in text:
if c not in (string.ascii_lowercase+string.ascii_uppercase):
chiper += c
continue
offset = ord(key[index]) - (ord('a') if key[index].islower() else ord('A'))
_ord = ord('a') if c.islower() else ord('A')
encrypted_c = chr((ord(c) - _ord + offset) %26 + _ord)
chiper += encrypted_c
index = (index + 1) % len(key)
Что позволит нам избавиться от continue без явной вложенности if:
for c in text:
if c in (string.ascii_lowercase+string.ascii_uppercase):
offset = ord(key[index]) - (ord('a') if key[index].islower() else ord('A'))
_ord = ord('a') if c.islower() else ord('A')
encrypted_c = chr((ord(c) - _ord + offset) %26 + _ord)
chiper += encrypted_c
index = (index + 1) % len(key)
else:
chiper += c