Search code examples
pythonvariablesdecodeencodescramble

How to scramble the letters of a variable in python


Im trying to make it so you type in a word and then a password and then it outputs the word with the letters scrambled up and then a separate program to decode it. I have tried to use Import Random but it hasn't worked. I have been looking online for about an hour and still haven't found anything. Here is the code I have so far.

ss = raw_input ("Enter Plain Text Here:  ")
password = raw_input ("Enter the Password here:  ")
RealPassword = "Test Password"
if password == RealPassword:
    print "Password Accepted!"
    Var1 = (ss[1])
    Var2 = (ss[2])
    Var3 = (ss[3])
    Var4 = (ss[4])
    Var5 = (ss[5])
    Var6 = (ss[6])
    Var7 = (ss[7])
    Var8 = (ss[8])
    Var9 = (ss[9])
    Var10 = (ss[10])
    Var11 = (ss[11])
    Var12 = (ss[12])
    Var13 = (ss[13])
    Var14 = (ss[14])
    Var15 = (ss[15])
    Var16 = (ss[16])
    Var17 = (ss[17])
    print Var1 + Var2 + Var3 + Var4 + Var5 + Var6 + Var7 + Var8 + Var9 
else:
    print "Wrong"

Solution

  • Here's a basic answer. There's an encoding function which passes back a "key" (which is called seed in my code) for the decoder to read. This takes advantage of two things: The shuffle function in python, and the fact that random number generators in python are in fact pseudorandom -- they actually have repeatable behavior.

    Also, credit to Hugh in this post which I used a lot in crafting my answer.

    import random
    
    def encoder(word):
        seed = random.randint(1,100)
        random.seed(seed)
        l = list(word)
        random.shuffle(l)
        scrambled_word = ''.join(l)
        return seed, scrambled_word
    
    def decoder(seed, scrambled_word):
        random.seed(seed)
        order = list(range(len(scrambled_word)))
        random.shuffle(order)
    
        original_word = [0]*len(scrambled_word)
        for index,original_index in enumerate(order):
            original_word[original_index] = scrambled_word[index]
        print(''.join(original_word))
    
    
    original_word = "hello"
    
    seed, scrambled_word = encoder(original_word)
    print(scrambled_word)
    decoder(seed, scrambled_word)
    

    Feel free to ask any questions if something doesn't make sense.