Search code examples
pythonalphabet

How do I link random numbers to letters of the alphabet, no duplicates


My aim is to ultimately create a puzzle that can allow users to input a phrase, encode it to numbers and then allow them to figure out the phrase by slowly working out what number is what for the alphabet.

Although I don't want a=1, b=2 ect because that would be too easy.

So far i have been able to do this, the long way round but even this does not exclude duplicates:

Letters get random numbers:

import random 

a = random.randint(1, 26)
b = random.randint(1, 26)
c = random.randint(1, 26)
d = random.randint(1, 26)
e = random.randint(1, 26)
f = random.randint(1, 26)
g = random.randint(1, 26)
h = random.randint(1, 26)
i = random.randint(1, 26)
j = random.randint(1, 26)
k = random.randint(1, 26)
l = random.randint(1, 26)
m = random.randint(1, 26)
n = random.randint(1, 26)
o = random.randint(1, 26)
p = random.randint(1, 26)
q = random.randint(1, 26)
r = random.randint(1, 26)
s = random.randint(1, 26)
t = random.randint(1, 26)
u = random.randint(1, 26)
v = random.randint(1, 26)
w = random.randint(1, 26)
x = random.randint(1, 26)
y = random.randint(1, 26)
z = random.randint(1, 26)

print ("a is:",a)
print ("b is:",b)
print ("c is:",c)
print ("d is:",d)
print ("e is:",e)
print ("f is:",f)
print ("g is:",g)
print ("h is:",h)
print ("i is:",i)
print ("j is:",j)
print ("k is:",k)
print ("l is:",l)
print ("m is:",m)
print ("n is:",n)
print ("o is:",o)
print ("p is:",p)
print ("q is:",q)
print ("r is:",r)
print ("s is:",s)
print ("t is:",t)
print ("u is:",u)
print ("v is:",v)
print ("w is:",w)
print ("x is:",x)
print ("y is:",y)
print ("z is:",z)

Solution

  • You can do the following, building a dict mapping from characters to unique numbers 1-26:

    import string, random
    
    nums = random.sample(range(1, 27), 26)
    code = dict(zip(string.ascii_lowercase, nums))
    # {'a': 8, 'b': 13, 'c': 20, 'd': 25, 'e': 10, 'f': 17, 
    #  'g': 2, 'h': 9, 'i': 12, 'j': 7, 'k': 15, 'l': 19, 'm': 26, 
    #  'n': 18, 'o': 24, 'p': 4, 'q': 21, 'r': 5, 's': 3, 't': 1, 
    #  'u': 16, 'v': 22, 'w': 14, 'x': 23, 'y': 11, 'z': 6}
    

    For decoding, you can just use the backwards mapping:

    decode = dict(zip(nums, string.ascii_lowercase))