【发布时间】:2015-01-07 04:11:23
【问题描述】:
所以下面是一些能够编码和解码句子的 Python 代码。我不确定如何定义一个函数,该函数采用三个参数,可以概括或组合这两个函数:mapInToOutEncode 和 mapInToOutDecode 合二为一。
alphabet = " abcdefghijklmnopqrstuvwxyz"
keyString ="kjihgfedcba zyxwvutsrqponml"
def mapInToOutEncode(inChar):
index = 0
found = 0
for char in alphabet:
if(char == inChar):
found = index #remember it in a variable found
else:
index +=1
outChar = keyString[found]
return(outChar)
def mapInToOutDecode(inChar):
index = 0
found = 0
for char in alphabet:
if(char == inChar):
found = index #remember it in a variable found
else:
index +=1
outChar = keyString[found]
return(outChar)
def encode(inString):
outString = ''
for char in inString:
outString += mapInToOutEncode(char)
return(outString)
def decode(inString):
outString = ''
for char in inString:
outString += mapInToOutDecode(char)
return(outString)
print( encode("this is a crazy bit of news to share we attack at dawn" ))
print( decode(encode("this is a crazy bit of news to share we attack at dawn")))
【问题讨论】:
-
这实际上不是“如何组合功能”的答案,但您正在寻找的功能已经在
str.translate()中实现,另请参见string.maketrans()。
标签: python string python-3.x decode encode