返回(key_code,已解码)的元组

时间:2017-07-31 13:25:11

标签: 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_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')

2 个答案:

答案 0 :(得分:0)

首先,您创建请求的词典,然后传递"解码"穿过它。

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"))

答案 1 :(得分:0)

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