【问题标题】:Caesar Cipher with capital letters大写字母的凯撒密码
【发布时间】:2019-03-03 02:58:01
【问题描述】:

所以目前我的凯撒密码程序在我使用小写字母时运行良好。但是,当我输入大写的单词或短语时,我希望它能够工作。这是我现在拥有的代码。希望大家能帮我完成这个。

用户定义函数

def 加密(消息,距离): """将获取消息并将其旋转距离,以创建加密消息"""

encryption = ""
for ch in message:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    if cipherValue > ord("z"):
        cipherValue = ord("a") + distance - (ord("z") - ordvalue + 1)
    encryption += chr(cipherValue)
return encryption

def 解密(消息,距离): """将解密上面的消息"""

decryption = ""
for cc in message:
    ordvalue = ord(cc)
    decryptValue = ordvalue - distance
    if decryptValue < ord("a"):
        decryptValue = ord("z") - distance - (ord("a") - ordvalue - 1)
    decryption += chr(decryptValue)
return decryption

def 二进制转换(消息): """将单词转换成二进制码"""

binary = ""
for cb in message:
    binaryString = " " #Binary number
    binaryNumber = ord(cb)
    while binaryNumber > 0:
        binaryRemainder = binaryNumber % 2
        binaryNumber = binaryNumber // 2
        binaryString = str(binaryRemainder) + binaryString
    binary += binaryString
return binary

while 循环

运行 = 真

运行时:

#input 

message = input("Enter word to be encrypted: ") #original message
distance = int(input("Enter the distance value: ")) #distance letters will be moved

#variables

fancy = encrypt(message, distance)
boring = decrypt(fancy, distance)
numbers = binaryConversion(message)

#output
print("\n")
print("Your word was: ", format(message, ">20s"))
print("The distance you rotated was: ", format(distance), "\n")
print("The encryption is: ", format(fancy, ">16s"))
print("The decryption is: ", format(boring, ">16s"))
print("The binary code is: ", format(numbers)) #I know an error comes here but it will work in the end

repeat = input("Would you like to encrypt again? Y/N ")
print("\n")
if repeat == "N" or repeat == "n":
    run = False
else:
    run = True

结局

print("谢谢你,正如 Julius Caesar 曾经说过的,'Veni, vidi, vici'")

谢谢

【问题讨论】:

  • 我想我错过了解释。我试过了,但我还需要用大写字母从解密中打印出来

标签: python caesar-cipher


【解决方案1】:

我建议您以映射而不是偏移的心态来解决这个问题。您可以根据偏移量构建映射,但如果您使用字典或其他形式的一对一映射,字符处理会更容易。

例如:

  offset = 5
  source = "abcdefghijklmnopqrstuvwxyz"
  target = source[offset:]+source[:offset]
  source = source + source.upper()
  target = target + target.upper()
  encrypt = str.maketrans(source,target)
  decrypt = str.maketrans(target,source)

  e = "The quick brown Fox jumped over the lazy Dogs".translate(encrypt)
  print(e)
  d = e.translate(decrypt)
  print(d)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2020-05-31
    相关资源
    最近更新 更多