Kins Lau
Kins Lau

Reputation: 39

How to decrypt a string that I know its pattern in Python?

I'm working on an encrypted string that is made up of 5 integers, and I figured out its pattern, I tried to write a python OrderedDict like this:

od = OrderedDict([('0', '9'), ('1', '2'), ('2', '0'), ('3', '7'), ('4', '1'), 
                  ('5', '3'), ('6', '8'), ('7', '6'), ('8', '5'), ('9', '4')])

So I wrote some codes to decrypt the string.
The "encrypted" string is an example.

def replace_all(text, dic):
    for k, v in dic.items():
        text = text.replace(k, v)
    return text


encrypted = '14012'
decrypted = replace_all(encrypted, od)

I just can't get the correct answer, the string 14012 should be decrypted to 21920,but I just get 01400.

What should I do with my codes to get the correct string?

Upvotes: 2

Views: 118

Answers (2)

bison
bison

Reputation: 747

@blhsing has it right, think about what happens to text each loop:

>>> decrypted = replace_all(encrypted, od)
14912
24922
04900
01900
01400

You will want to translate item by item

I like ''.join([od[i] for i in encrypted])

Upvotes: 2

blhsing
blhsing

Reputation: 107015

You iterate over the dict items one by one, so '1' gets translated to '2', and then '2' gets translated to '0', which is why the result starts with '0' instead of '2', for example.

You can use the str.translate() method instead:

table = ''.join(od.get(chr(i), chr(i)) for i in range(256))
print(encrypted.translate(table))

This outputs:

21920

There's no need to use OrderedDict in this case, by the way, since order does not matter in building the translation table.

Upvotes: 3

Related Questions