Skip to content Skip to sidebar Skip to footer

Why My Code Does Not Decode The Encrypted String Based On The Dictionary?

I have a dictionary with keys and values that represent letters. for example a simple one : DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'} I've received an enc

Solution 1:

Changing the word variable inside the for loop, would not change the string inside the word_list. You would need to remember the index and update the element at that index (and get the word from the index) -

for i, word in enumerate(words_list):
    for char in word:
            if char in string.letters:
                    words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))

Demo -

>>> words_list = ["bppx","xnt!"]
>>> DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}
>>> for i, word in enumerate(words_list):
...     for char in word:
...             if char in string.letters:
...                     words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
>>> words_list
['good', 'day!']

But an easier way for you would be to use str.translate (along with string.maketrans ). Example -

table = string.maketrans('bnpxt','gaody') #First argument characters in your original string, and second argument what they map to.
for i, word in enumerate(words_list):
    words_list[i] = word.translate(table)

Demo -

>>> import string
>>> table = string.maketrans('bnpxt','gaody')  #This creates the translation table
>>> words_list = ["bppx","xnt!"]
>>> for i, word in enumerate(words_list):
...     words_list[i] = word.translate(table)
... 
>>> print words_list
['good', 'day!']

This using list comprehension -

words_list[:] = [word.translate(table) for word in words_list]

Demo -

>>> words_list = ["bppx","xnt!"]
>>> table = string.maketrans('bnpxt','gaody')
>>> words_list[:] = [word.translate(table) for word in words_list]
>>> words_list
['good', 'day!']

Solution 2:

Your problem is that you don't actually modify original list.

for i, word in enumerate(words_list):
    for char in word:
        if char in string.letters:
            word = word.replace(char, DICT_CODE.get(char))
            words_list[i] = word

print words_list

['good', 'day!']

Solution 3:

As mentioned in the comments, by @marmeladze, print word_list will print the word_list which you declared above.

What you want, is something like this:

DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y', '!': '!'}

words_list = ["bppx","xnt!"]

decoded_list = []

for word in words_list:

    for char in word:    
            word = word.replace(char, DICT_CODE.get(char))
    decoded_list.append(word)

print decoded_list

Output

['good', 'day!']

Hope this helps.


Post a Comment for "Why My Code Does Not Decode The Encrypted String Based On The Dictionary?"