我正在制作一个程序,接受一个句子并将其搞砸,直到通过“degarbler”
Theres可能是一个更好的方法来做到这一点,但如果每个人都能告诉我如何解决我做错的事情,我将不胜感激
def sencoder (sentence):
sentence = sentence.replace ("a","h")
sentence = sentence.replace ("s","j")
sentence = sentence.replace ("d","k")
sentence = sentence.replace ("f","l")
sentence = sentence.replace ("b","g")
sentence = sentence.replace ("z","t")
sentence = sentence.replace ("q","y")
sentence = sentence.replace ("w","u")
sentence = sentence.replace ("e","i")
sentence = sentence.replace ("r","o")
sentence = sentence.replace ("x","p")
sentence = sentence.replace ("c","b")
sentence = sentence.replace ("v","n")
sentence = sentence.replace ("m","m")
print sentence
def decoder (sentence):
sentence = sentence.replace ("h","a")
sentence = sentence.replace ("j","s")
sentence = sentence.replace ("k","d")
sentence = sentence.replace ("l","f")
sentence = sentence.replace ("g","b")
sentence = sentence.replace ("t","z")
sentence = sentence.replace ("y","q")
sentence = sentence.replace ("u","w")
sentence = sentence.replace ("i","e")
sentence = sentence.replace ("o","r")
sentence = sentence.replace ("p","x")
sentence = sentence.replace ("b","c")
sentence = sentence.replace ("n","v")
sentence = sentence.replace ("m","m")
print sentence
sentence = ""
choice = raw_input ("Do you want to decode or encode: ").lower()
while sentence != "quit":
sentence = raw_input("Enter the code: ")
if choice == "encode":
decoder(sentence)
elif choice == "decode":
sencoder(sentence)
else:
print "Please make a valid decision"
帮助
答案 0 :(得分:5)
以下是提示:改为使用translate
方法。
>>> import string
>>> t = string.maketrans("abcdef", "bcdefa")
>>> "abracadabra".translate(t)
'bcrbdbebcrb'
>>> t2 = string.maketrans("bcdefa", "abcdef")
>>> "bcrbdbebcrb".translate(t2)
'abracadabra'
答案 1 :(得分:2)
我正在制作一个程序,接受一个句子并将其搞砸,直到通过“degarbler”
请注意,这不适用于任何类型的输入句子:
encode ("ah") = "hh" decode ("hh") = "aa"
如果两个字母可以重叠,则需要更改算法以使部分编码数据与输入字符串分开。
从你的例子来看,如果这是一个问题并不明显,但我认为我最好指出它。
答案 2 :(得分:1)
你的脚本“对我有用”。也许困扰你的是你的编码和解码的意义是什么?
也就是说,输入“encode”会调用您的解码器,输入“decode”会调用您的编码器。
正如您在评论中看到的那样,请使用translate
! :)