【问题标题】:Unable to get desired output for Caesar Cypher无法为 Caesar Cypher 获得所需的输出
【发布时间】:2022-01-22 21:51:54
【问题描述】:

我正在尝试为 Caesar Cypher 创建一个函数,该函数使用 ord() 函数将任何字符串转换为其各自的 unicode,然后将 unicode 移动两步。

例如,字符串“a”的 unicode 是整数 97。

print(ord('a'))

之后,这个移位的 unicode 被转换回其各自的字符,以产生一段难以理解的代码。

。回溯(最近一次通话最后): 文件“main.py”,第 11 行,在 密码(味精) 文件“main.py”,第 9 行,在 Ccypher 中 a = a + str(chr(lst[i])) UnboundLocalError:在赋值之前引用了局部变量“a”**

我尝试通过添加将 a 转换为全局变量 global a 在函数体中,但我没有输出,只是空白。

我写的代码如下:

lst = list()
a = ''
msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt

def Ccypher(string, shift = 2):
    for i in range(len(msg)):
        lst.append(ord(msg[i]) + shift)
        a = a + str(chr(lst[i]))
    return a
Ccypher(msg)

【问题讨论】:

  • 这不是真正的凯撒,因为您会将任何字符翻译成另一个(可能不可打印或当前编解码器中不存在)一个,而 官方 凯撒密码将字母转换为字母.是否是一个问题取决于你......

标签: python encryption unicode cypher list-manipulation


【解决方案1】:

在我的机器上,添加了global aCcypher(msg) 的返回值不为空:'Oggv"og"cv"vjg"Tkv|"Ectnvqp"cv";"q)enqem."fqp)v"dg"ncvg#'。你可能只是忘记打印了

【讨论】:

    【解决方案2】:

    如前所述,所有变量都应该在函数内部声明,这里不需要全局变量(这通常是不好的做法)。

    并且只打印你的函数返回的最终结果,否则它会被计算但会丢失:

    def Ccypher(string, shift = 2):
        lst = list()
        a = ''
        for i in range(len(msg)):
            lst.append(ord(msg[i]) + shift)
            a = a + str(chr(lst[i]))
        return a
    
    msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt
    
    print(Ccypher(msg))
    

    PS 原版 Caesar Cypher 偏移了 3 个字母

    【讨论】:

      【解决方案3】:

      没有全局变量可以很容易地解决这个问题。您需要在循环之前在函数体中声明变量,您还需要不仅调用函数,还需要打印其结果:

      msg = "Meet me at the Ritz Carlton at 9 o'clock, don't be late!" #message to encrypt
      
      def Ccypher(string, shift = 2):
          a = ''
          lst = list()
          for i in range(len(msg)):
              lst.append(ord(msg[i]) + shift)
              a = a + str(chr(lst[i]))
          return a
      print(Ccypher(msg))
      

      请注意,您的“密码”不是真正的Caesar cipher。凯撒密码应该只编码字母(在这种情况下,是字母,而不是其他符号),不包括标点符号和数字

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-12
        • 2017-07-04
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 2015-04-06
        相关资源
        最近更新 更多