Skip to content Skip to sidebar Skip to footer

Confusion With Encryption

I'm trying to write a program that generates a list with the numbers from 1 to 26 in random order, then 'encrypts' a given word using that list so that the n'th letter of the alpha

Solution 1:

My take on it:

from string import ascii_lowercase
from random import shuffle

defchar2num(chars):
    r = range(len(chars))
    shuffle(r)
    returndict(zip(chars, r))

defencrypt(s, lookup):
    return' '.join(str(lookup[ch]) for ch in s)

print encrypt('cat', char2num(ascii_lowercase))

Solution 2:

import random
import string

def randomalpha():
    nums, result = range(26), [] # [0, 1, 2, 3, ... --> 25]
    random.shuffle(nums)
    for i in range(26):
        result.append(nums.pop())
    return result

def encrypt(s):
    alphabet = list(string.lowercase) # ['a', 'b', 'c', ... --> 'z']
    key = dict(zip(alphabet, randomalpha()))
    return ''.join([str(key[ltr]) for ltr in s])

References:

Solution 3:

Adding this here because of this question asked today: Easiest way to assign a number to the alphabet?

 import random, string
    alpha = list(string.ascii_lowercase)
    numLst = list()
    whilelen(numLst) != 26:
        num = random.randint(1,26)
        if (num notin numLst):
            numLst.append(num)

Now all you have to do is index the lists to get the letter and corresponding unique random number. For instance alpha[0] gives you "a" and numLst[0] would give you corresponding unique number.

Post a Comment for "Confusion With Encryption"