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): pas
Solution 1:
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!
Solution 2:
Solution 3:
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)
Post a Comment for "Using A Key To Rearrange String"