【问题标题】:python building coder for ceasar cipher凯撒密码的python构建代码
【发布时间】:2013-10-08 21:04:25
【问题描述】:

所以我应该构建一个编码器,通过给定的移位值移动字母的值。 我制作了 2 个字典,1 个用于小写字母,1 个用于大写字母。

这是它应该做的: “返回一个可以将凯撒密码应用于字母的字典。 密码由移位值定义。忽略非字母字符 比如标点符号和数字。”

这是一个例子:

例子:

>>> build_coder(3)
{' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J',
'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O',
'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X',
'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd',
'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l',
'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q',
'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z',
'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'}
(The order of the key-value pairs may be different.)
"""

从 2 个不完整的大小写字母字典开始:

capitals = {'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', ' '}
lower = {'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', ' '}            

【问题讨论】:

  • 对,Stackoverflow 是一个充满了无所事事的极客,整天坐在那里等待机会为你做作业的地方。
  • 嗯,它带来了一些好处:我忘记了集合的语法。当然,这是一个非常糟糕的开始,因为凯撒密码是基于集合不保留的字母顺序。顺便问一下,为什么这个代码中的空格是一个字母?
  • 请向我们展示您到目前为止编写的代码。 SO 最擅长回答具体问题或调试功能失调的代码。如果您只有问题描述,您可能会从tutorial 获得比问答网站更多的好处。
  • @Kevin 是否有 StackExchange 站点可用于调试功能失调的系列?我的代码总是有效的。随着假期的临近,我想我可以使用前者。

标签: python dictionary encryption


【解决方案1】:

您不必使用字典...有一种更简单的方法,使用string 模块:

from string import printable, maketrans

def caesar(string, key):

    shifted_alphabet = printable[key:] + printable[:key]
    table = maketrans(printable, shifted_alphabet)
    return string.translate(table)

string = raw_input("Enter something> ") #input for python 3
while 1:
    try:
        key = int(raw_input("Enter key (0-25): "))
    except:
        print "Key should be integer"
    else:
        if not (0 <= key <= 25):
            print "Key should 0-25, %s received"%key
            continue
        break
print caesar(string, key)
print caesar(string, len(printable)-key)

【讨论】:

  • uncaesar 真的是 caesar(..., len(alphabet)-key)。干燥
  • 还有……key in range(26)?也许0 &lt;= key &lt; 26 会是更好的选择;)
猜你喜欢
  • 2013-03-13
  • 1970-01-01
  • 2020-11-12
  • 2014-03-30
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多