Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回(键\代码,解码)的元组_Python - Fatal编程技术网

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á!

你复习了课程材料吗?你不了解的是什么?所有这些都有非常详细的解释,你甚至有一些例子。别忘了使用搜索框?