0

我想创建一个简单的密码。

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  while True:
      plain = raw_input("text to be encoded: ")
      print encode(plain)

def encode(plain):
      length = len(plain)
      plain = plain.upper()
      for c in plain:
          encoded = _______
      return encoded 

输入:CAT,输出:MXU

我有这个模板,但是最好的方法是什么?如果我必须使用字典,我该如何在给定的设置中使用它?

4

3 回答 3

3

一个非常有效的方法是使用.translate()字符串的方法:

import string

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

cipher = string.maketrans(alpha, key)

def encode(plaintext):
    return plaintext.translate(cipher)
于 2013-10-26T23:11:17.637 回答
2

With your two strings:

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

Create a dictionary using zip():

mydict = {k:v for k, v in zip(alpha, key)} # Or dict(zip(alpha, key))

Then in your encode() function, you can just do:

def encode(plain):
    return ''.join([mydict.get(i, i) for i in plain])

[mydict.get(i, i) for i in plain] Is equivalent to:

newlist = []
for i in plain:
    newlist.append(mydict.get(i, i))

mydict.get(i, i) is equivalent to mydict[i], but if there is no key i, then i (the second parameter) is returned (instead of raising a KeyError)

Note that the list will return something like ['M', 'X', 'U'], so the ''.join() will print it as 'MXU'

于 2013-10-26T23:08:15.357 回答
1
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

inp = 'CAT'

_d = {e[0]: e[1] for e in zip(alpha, key)}

print _d


print ''.join([_d[ele] for ele in inp if ele in _d])
于 2013-10-26T23:14:04.050 回答