【问题标题】:Caesar cypher in PythonPython 中的凯撒密码
【发布时间】:2014-03-30 08:18:46
【问题描述】:

我是 python 新手,我想编写一个程序,要求输入一行(每个数字将由一个空格分隔。)它将使用简单的字母数字替换密码。每个字母都会被指定一个编号。所以 1 = a、2 = b 和 3 = c 直到达到 26 = z。然而,从那里开始,密码将继续如此; 27 = a、28 = b 等等。0 将是一个空格。该程序将仅使用 0 和正数。它还将打印出消息的解密。例如:

请输入代码: 8 5 12 12 15

你好

还有一个例子:

请输入代码: 16 25 20 8 14 0 9 19 0 3 15 15 12

python 很酷

目前我已经尝试将字母表变成这样的列表;

    n = int(input("Please type a code: ")
    x =['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']

...然后稍后再提及。但是,我不确定这将如何工作。我也尝试过使用 .replace() 函数。像这样:

    n = int(input("Please type a code: ")
    n = n.replace('1','a') #all the way until z and then loop it.
    print(n)

等等等等。但同样,我不知道如何正确地做到这一点。 任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 不要再发same question
  • 右侧似乎至少有十几个Caesar cipher 问题(在相关列表中)。努力自己做功课。您提供的几行代码与您想要实现的目标相差甚远。

标签: python encryption substitution


【解决方案1】:

使用split()

numbers = input("Please type a code: ").split()

# ['16', '25', '20', '8', '14', '0', '9', ',19', '0', '3', '15', '15', '12']

使用for .. in ..

for num in numbers:
    print( x[int(num)] )

如果您使用0 作为space,则必须在列表的开头添加space

x = [' ', 'a', 'b', 'c', .... ]

现在x[0] == ' '

【讨论】:

    【解决方案2】:

    只需创建如下函数:

    >>> def numerate(char):
    ...    alpha = 'abcdefghijklmnopqrstuvwxyz'
    ...    place = alpha.index(char)
    ...    return alpha
    ...
    >>> sent = raw_input('Enter your sentence to be encrypted: ')
    Enter your sentence to be encrypted: python is so cool
    >>> encrypted = []
    >>> for k in sent:
    ...    encrypted.append(numerate(k))
    ...
    >>> encrypted
    [15, 24, 19, 7, 14, 13, 26, 8, 18, 26, 18, 14, 26, 2, 14, 14, 11]
    

    现在您只需将其反转为“枚举”或解码。

    【讨论】:

      【解决方案3】:

      希望对您有所帮助!这是我的简单凯撒密码

      加密代码

      l=[' ','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']
      demeg=raw_input("plz enter your message for encryption:")
      key=raw_input('Enter your encryption key(key must be a number): ')
      m=list(demeg)
      le=len(m)
      message=[]
      j=0
      while le>0:
          p=[i for i,x in enumerate(l) if x == m[j]]
          p=p[0]
          p=p+int(key)
          p=str(p)
          message.append(p)
          j+=1
          le-=1
      
      message=' '.join(message)   
      print message
      

      这是我的解密代码

      l=[' ','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']
      get=raw_input('Please type a code for decryption: ')
      key=raw_input('Enter your secret decryption key: ')
      st=str(get)
      m=st.split()
      n=len(m)
      i=0
      message=[]
      while n>0:
      
          s=m[i]
          s=int(s)
          s=s-int(key)
          if s>26:
              s=s-26
          word=l[s]
          message.append(word)
          i+=1
          n-=1
      meg=''.join(message)
      print meg 
      

      【讨论】:

        最近更新 更多