发布
社区首页 >问答首页 >凯撒密码不起作用,不知道出了什么问题

凯撒密码不起作用,不知道出了什么问题
EN

Stack Overflow用户
提问于 2022-04-04 00:25:44
回答 3查看 193关注 0票数 -1

我需要创建一个简单的凯撒密码编码器/解码器,我不确定最好的方法,字符串?名单?循环?

代码语言:javascript
代码运行次数:0
复制
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循环来分离列表项并进行比较,但是它没有工作,所以我不知道如何继续,不能使用translateorder函数。

EN

回答 3

Stack Overflow用户

发布于 2022-04-04 00:34:12

  • 您的alphabet列表至少缺少一个字母,因此这可能会影响您的结果。我建议用string.ascii_uppercase代替.

  • 在声明if letters == [alphabet.index(letters)]中,你混淆了这个字母(letters --实际上这只是一个字母!)对于字母的indexalphabet;它们不可能是相同的,因为一个是字符串,另一个是int。无论如何,您不需要循环来查找索引;index函数会为您执行此操作。

  • 一定要“包装”字母表末尾的移位!mod (%)操作符是一种简单的方法。

  • 小心没有出现在alphabet中的字符。

代码语言:javascript
代码运行次数:0
复制
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
))
代码语言:javascript
代码运行次数:0
复制
What do you want to decode? ZEBRA STRIPES
What do you want the shift to be? 12
LQNDM EFDUBQE
票数 0
EN

Stack Overflow用户

发布于 2022-04-04 01:38:12

使用这个循环

代码语言:javascript
代码运行次数:0
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2022-04-04 01:48:41

代码语言:javascript
代码运行次数:0
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71730867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档