我需要創建一個簡單的凱撒密碼編碼器/解碼器,但我不確定最好的方法,字串?清單?回圈?
Word = input("What do you want to decode")
Shift = input("What do you want the shift to be?")
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"]
for letters in Word:
if letters == [alphabet.index(letters)]:
print [alphabet.index(letters Shift)]
for a in alphabet:
if a == letters:
print (letters (alphabet.index(letters)))
如您所知,我嘗試for使用回圈來分隔串列項并進行比較,但它不起作用,所以我不確定如何繼續,無法使用translateororder函式。
uj5u.com熱心網友回復:
您的
alphabet串列至少缺少一個字母,因此可能會影響您的結果。我建議string.ascii_uppercase改用。在宣告中
if letters == [alphabet.index(letters)],您將字母(letters--這實際上只是一個字母!)與index中的字母混淆了alphabet;它們不可能永遠相同,因為一個是字串,另一個是 int。無論如何,您都不需要回圈查找索引;該index功能為您做到這一點。確保將移位“包裹”在字母表的末尾!mod (
%) 運算子是一種簡單的方法。小心那些根本不在的角色
alphabet。
import string
word = input("What do you want to decode? ").upper()
shift = int(input("What do you want the shift to be? "))
alphabet = string.ascii_uppercase
print(''.join(
alphabet[
(alphabet.index(c) shift) % len(alphabet)
] if c in alphabet else c for c in word
))
What do you want to decode? ZEBRA STRIPES
What do you want the shift to be? 12
LQNDM EFDUBQE
uj5u.com熱心網友回復:
word = input("What do you want to decode ")
shift = input("What do you want the shift to be? ")
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"]
def caesar_encrypt(word: str, shift: int):
return ''.join(alphabet[(alphabet.index(char) shift) % len(alphabet)]
if char in alphabet else char for char in word)
def caesar_decript(word: str, shift: int):
return caesar_encrypt(word, 26-shift)
word = word.upper()
shift = int(shift)
encrypted_word = caesar_encrypt(word, shift)
print(encrypted_word)
decripted_word = caesar_decript(encrypted_word, shift)
print(decripted_word)
uj5u.com熱心網友回復:
使用這個回圈
import string
Word = input("What do you want to decode")
Shift = input("What do you want the shift to be?")
alphabet = string.ascii_uppercase
ouput = ""
for i in Word:
if i.upper() in alphabet:
if alphabet.find(i.upper()) int(Shift)>25:
ouput = alphabet[alphabet.find(i.upper()) int(Shift)-25]
else:
ouput = alphabet[alphabet.find(i.upper()) int(Shift)]
else:
ouput =i
print(ouput)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455736.html
