简体   繁体   中英

python itertools.permutations combinations

I have this variable: message = "Hello World" and I built a function that shuffles it:

def encrypt3(message,key):
    random.seed(key)
    l = range(len(message))
    random.shuffle(l)
    return "".join([message[x] for x in l])

This function just suffle the message so it could look like this for example "Hrl llWodeo"

Now if I want to convert it to the message again using itertools.permutations, how can I do it? When I tried this : print [x for x in itertools.permutations(shuffledMsg)] the program closed with error because its has to many posibilities.

This is of course "unshuffable" so long as you know the original seed, since we can simply re-run it to find out where each character is shifting to.

import random

def encrypt3(message,key):
    random.seed(key)
    l = range(len(message))
    random.shuffle(l)
    return "".join([message[x] for x in l])


key = 'bob'
message = 'Hello World!'

print(encrypt3(message, key))


def unshuffle(message, key):
    random.seed(key)
    new_list = list(range(len(message)))
    old_list = [None] * len(new_list)

    random.shuffle(new_list)

    for i, old_i in enumerate(new_list):
        old_list[old_i] = message[i]

    return ''.join(old_list)


print(unshuffle(encrypt3(message, key), key))

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