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:
- can assume key is hashable, but may be multiple types
- definition of section for ignacio 开发者_高级运维
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!
you can reinvent the wheel, but why not try an encryption library first, if possible.
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)
精彩评论