I'm trying to write an encryption program that generates 8 different random numbers and converts them to ASCII. If possible I'd like to use the 'random' function in python, but welcome other help.
So far my code for generating the numbers is to assign a value to a different run of the random.randint() function 8 different times, the problem is that this is sloppy. A friend said to use random.sample(33, 126, 8) but I can't get this to work.
Any help is extremely welcome.
You can pass xrange with your upper and lower bound to sample:
from random import sample
print(sample(xrange(33, 126),8))
An example output:
[49, 107, 83, 44, 34, 84, 111, 69]
Or range for python3:
print(sample(range(33, 126),8))
Example output:
[72, 70, 76, 85, 71, 116, 95, 96]
That will give you unique numbers.
If you want 8 variables:
a, b, c, d, e, f, g, h = sample(range(33, 126), 8)
If you want ascii you can map(chr..):
from random import sample
print map(chr,sample(xrange(33, 126), 8))
Example output:
['Z', 'i', 'v', '$', ')', 'V', 'h', 'q']
Using random.sample is technically not what you want - the values are not independent since after you choose the first number (from 93 options) you only have 92 options for the second number and so on.
If you're ok with that you can use Padraic's answer.
If n (in your case n = 8) is much smaller than N (in your case N = 126-33 = 93) this should be fine, but the correct answer will be
a, b, c, d, e, f, g, h = [random.randint(93, 126) for _ in xrange(8)]
edit: More importantly, if you decide to increase n to a state where n > N, you'll get a ValueError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With