Python, substitution cipher [closed]

↘锁芯ラ 提交于 2019-12-13 11:25:34

问题


I need to write a substitution cipher for the digits 0,1,2,3,...,9 substitutes each digit in 0,1,2,3,...,9. It can be represented as a 10 digit string specifying how each digit in 0,1,2,3,...,9 is substituted. For example, the 10 digit string '3941068257' specifies a substitution cipher in which digit 0 is substituted with digit 3, 1 with 9, 2 with 4, and so on. To encrypt a non negative integer, substitute each of it's digits with the digit specified by the encryption key. Implement function cipher() that takes as in put a 10 digit string key and a digit and a digit string (i.e., the clear text to be encrypted) and returns the encryption of the clear text.

>>>encrypt('3491068257', '132')
'914'
>>>encrypt('3491068257', '111')
'999'

Thank you for your help :)


回答1:


from string import maketrans

zero_through_nine = "".join(str(i) for i in range(10))
out_tab = "3491068257"
trantab = maketrans(zero_through_nine,out_tab )
print "111".translate(trantab)

hopefully you look into it to understand it....




回答2:


I would like to see an attempt out of the OP posted, but anyway

def encrypt(key,s):
    return ''.join(key[int(c)] for c in s)

This uses each "key" in the string, and uses that to look up the appropriate character.




回答3:


In the encrypt function you could create a map of lookups using the first string parameter. Then go through each character in the second parameter string and use this map for substitution and create and return a new string



来源:https://stackoverflow.com/questions/15583375/python-substitution-cipher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!