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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With