Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 897
hoju Avatar asked Feb 27 '23 11:02

hoju


2 Answers

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!
like image 62
Mark Byers Avatar answered Mar 08 '23 07:03

Mark Byers


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

like image 29
ghostdog74 Avatar answered Mar 08 '23 05:03

ghostdog74