hoju
hoju

Reputation: 29472

using a key to rearrange string

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:

Upvotes: 4

Views: 1325

Answers (3)

sth
sth

Reputation: 229784

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)

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342819

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

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838926

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!

Upvotes: 4

Related Questions