python - Python 中的替代加密(ProblemSetQuestion)

标签 python encryption python-3.x

Winkleson 在这里提出另一个关于 http://singpath.appspot.com 的问题问题集问题。我是一名初学者程序员,只要有可能,我都希望得到一些指导。无论如何,我在这里提出了这个问题,我不确定如何通过比较每个.SINGLE.LETTER 来进行而不浪费时间。在 if 语句中。所以我希望有任何提示/解决方案来减少这个问题的编码。我会发布我目前所拥有的(不多)。提前致谢!

问题:


Substitution Encryption

Create a program that can be used to encrypt and decrypt a string of letters. The function should take input of a string to encode and a string of letters giving the new order of the alphabet. The second string contains all characters of the alphabet but in a new order. This order tells what letters to swap. The first letter in the second string should replace all the a's in the first string. The third letter of the second string should replace all c's in the first string. Your solution should be in all lower case. Be careful of punctuation and digits (these should not change).

示例(调用):

>>> encrypt('hello banana','qwertyuiopasdfghjklzxcvbnm')
'itssg wqfqfq'

>>> encrypt('itssg wqfqfq','kxvmcnophqrszyijadlegwbuft')
'hello banana'

>>> encrypt('gftw xohk xzaaog vk xrzxnkh','nxqlzhtdvfepmkoywrjiubscga')
'this code cannot be cracked'

>>> encrypt('mkhzbc id hzw pwdh vtcgxtgw ube fbicg ozth kbx tew fbicg','monsrdgticyxpzwbqvjafleukh')
'python is the best language for doing what you are doing'

我的代码:


def encrypt(s, realph):
    
    alph = 'abcdefghijklmnopqrstuvwxyz' #Regular Alphabet
    news = '' #The decoded string   
        
    #All comparison(s) between realph and alph    
        
    for i in range(len(realalph)):        
        
        #Comparison Statement here too.
        news = ''.join(alph) 
    
    return news

如您所见,这显然等同于失败的伪代码...一如既往,任何建议和/或解决方案都会很棒!提前致谢! - 温克尔森

最佳答案

这是一个翻译解决方案。

from string import maketrans

def encrypt(s, scheme):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    translation = maketrans(alphabet, scheme)
    return s.translate(translation)

字符串有一个内置的 translate 方法,允许您将单个字母与其他字母交换。令人难以置信的活泼,而且非常有用。

关于python - Python 中的替代加密(ProblemSetQuestion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500897/

相关文章:

Python 3 - 以不同形式对字符串格式的日期列表进行排序(带时间和不带时间)

python - 使用 numpy loadtxt 将导入字符串转换为 float

python - scipy.sparse.csr_matrix 的最大值

c++ - 加密/解密字节数组 Crypto++

C++ 暴力破解 XOR 密码

Java ssh-rsa 字符串到公钥

python - requirements.txt 与 setup.py

python - Apache 上的 Django 与 mod_wsgi CSRF 验证失败

python - Jupyter 笔记本无法在 VS Code 中打开

python - 为什么Kivy ActionBar不能正常工作?