views:

115

answers:

3

Using Python I want to randomly rearrange sections of a string based on a given key. I also want to restore the original string with the same key:

def rearrange(key, data):
    pass

def restore(key, rearranged_data):
    pass

Efficiency is not important. Any ideas?

Edit:

+4  A: 

Use random.shuffle with the key as a seed:

import random

def rearrange(key, data):
    random.seed(key)
    d = list(data)
    random.shuffle(d)
    return ''.join(d)

def restore(key, rearranged_data):
    l = len(rearranged_data)
    random.seed(key)
    d = range(l)
    random.shuffle(d)
    s = [None] * l
    for i in range(l):
        s[d[i]] = rearranged_data[i]
    return ''.join(s)


x = rearrange(42, 'Hello, world!')
print x
print restore(42, x)

Output:

oelwrd!, llHo
Hello, world!
Mark Byers
Mine was faster, but yours actually works -- so I deleted mine.
Cory Petosky
+3  A: 

you can reinvent the wheel, but why not try an encryption library first, if possible.

ghostdog74
That would be ideal because I am already using pycrypto. I didn't find such an algorithm there, but the docs are quite limited - does one exist?
Plumo
the algorithm in the library are all "tested" and widely used. your own algorithm will not be there. Pick the AES one and you will be fine
ghostdog74
thanks - AEA may be suitable. Pity all the docstrings are empty...
Plumo
+1  A: 

An implementation that reverses the shuffling with sort():

import random

def reorder_list(ls, key):
   random.seed(key)
   random.shuffle(ls)

def reorder(s, key):
   data = list(s)
   reorder_list(data, key)
   return ''.join(data)

def restore(s, key):
   indexes = range(len(s))
   reorder_list(indexes, key)
   restored = sorted(zip(indexes, list(s)))
   return ''.join(c for _, c in restored)
sth