简体   繁体   中英

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

My problem states:

Write a function, called decompress, that accepts a string and a dictionary as input. The dictionary maps special character strings to sequences of characters. The function goes through the argument string and if the character is in the dictionary, it converts it to the corresponding character sequence. Your solution may use iteration, but it MUST be recursive (it must call itself). Note that a special character may map to a sequence of characters that ALSO has a special character in it. For example, in Test One below, the symbol table maps '$' to the string ' y' and ' ' maps to 'c'. Hint: You can treat the resulting sequence as another string to decompress with the same symbol table.

Here is the code I currently have. I don't know how to take the values from the character sequence and convert them into the readable string. My code also raises a positional argument error.

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

Here are some output examples:

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

Your code is very close, I think you're just missing looking up the new/replacement characters in a_dict before calling the function again.

I think this is a correct solution?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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