Python 返回(键\代码,解码)的元组
我不明白这个问题。我需要一些提示:Python 返回(键\代码,解码)的元组,python,Python,我不明白这个问题。我需要一些提示: def cipher(map_from, map_to, code): """ map_from, map_to: strings where each contain N unique lowercase letters. code: string (assume it only contains letters also in map_from) Returns a tuple of (key
def cipher(map_from, map_to, code):
""" map_from, map_to: strings where each contain
N unique lowercase letters.
code: string (assume it only contains letters also in map_from)
Returns a tuple of (key_code, decoded).
key_code is a dictionary with N keys mapping str to str where
each key is a letter in map_from at index i and the corresponding
value is the letter in map_to at index i.
decoded is a string that contains the decoded version
of code using the key_code mapping. """
# Your code here
和测试用例,例如:
cipher(“abcd”、“dcba”、“dab”)
返回(字典中条目的顺序可能不同)({'a':'d','b':'c','d':'a','c':'b'},'adc')
首先,创建请求的字典,然后将“解码”字符串传递给它
def cipher(map_from, map_to, code):
key_code = {}
decoded = ''
for i in range(len(map_from)):
key_code[map_from[i]] = map_to[i]
for i in code:
decoded += key_code[i]
return (key_code,decoded)
print(cipher("abcd", "dcba", "dab"))
使用
dict()
和zip()
函数的简单解决方案:
def cipher(map_from, map_to, code):
D = dict(zip(map_from, map_to)) # create dictionary
msg = ""
for e in code:
msg += D[e] # encode message
return (D, msg) # voilá!
你复习了课程材料吗?你不了解的是什么?所有这些都有非常详细的解释,你甚至有一些例子。别忘了使用搜索框?