Using a key to reorder a string

Using Python I want to randomly reorder 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
source share
3 answers

you can invent the wheel, but why not try the encryption library , if possible.

+3
source

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) 

Conclusion:

 oelwrd!, llHo Hello, world! 
+4
source

An implementation that changes the shuffle 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) 
+1
source

Source: https://habr.com/ru/post/1302551/


All Articles