繁体   English   中英

如何将字典中的相应字符序列转换为可读字符串?

[英]How to convert corresponding character sequence from a dictionary into a readable string?

我的问题是:

编写一个名为 decompress 的 function,它接受一个字符串和一个字典作为输入。 字典将特殊字符串映射到字符序列。 function 遍历参数字符串,如果字符在字典中,则将其转换为相应的字符序列。 您的解决方案可能使用迭代,但它必须是递归的(它必须调用自身)。 请注意,特殊字符可能是 map 到其中也有特殊字符的字符序列。 例如,在下面的测试一中,符号表将“$”映射到字符串“ y”,而“ ”映射到“c”。 提示:您可以将生成的序列视为另一个字符串,以使用相同的符号表进行解压缩。

这是我目前拥有的代码。 我不知道如何从字符序列中获取值并将它们转换为可读的字符串。 我的代码还引发了位置参数错误。

def decompress(a_str, a_dict):

    new_string = ""

    for char in a_str:

        if char in a_dict:
            new_string.join(char)
        else: 
            sub_problem = decompress(char, a_dict)
            new_string.join(sub_problem)

    return new_string

以下是一些 output 示例:

    Examples:
    >>> d_simple = {'*':'c','#':'00','$':'*y'}
    >>> decompress('$3#',d_simple) #Test One
    'cy300'
    >>> d = {'#':'hem','@':'T#','$':'t#','&':'$ as','*':' do ','%':' to'}
    >>> d.update({'^':' someone ', '~':'for ', '+':'~&'})
    >>> decompress("@ as can*has%*+ can't. And^has% speak up + has no voices."  ,d) #Test Two
    "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."

您的代码非常接近,我认为您只是想在再次调用a_dict之前在 a_dict 中查找新/替换字符。

我认为这是一个正确的解决方案?

def decompress(string, table):
    new_string = ''
    for char in string:
        new_char = table.get(char, char)
        if new_char == char:
            new_string += char
        else:
            new_string += decompress(new_char, table)
    return new_string
d_simple = {'*': 'c', '#': '00', '$': '*y'}
print(decompress('$3#', d_simple))  # Test One
# 'cy300'
d = {'#': 'hem', '@': 'T#', '$': 't#', '&': '$ as', '*': ' do ', '%': ' to'}
d.update({'^': ' someone ', '~': 'for ', '+': '~&'})
print(decompress("@ as can*has%*+ can't. And^has% speak up + has no voices.", d))  # Test Two
# "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM