简体   繁体   中英

How do I generate 8 different random numbers in python?

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 your goal is to pick 8 random ASCII characters in the range [33..126], you can do that directly. First, ASCII characters in that range is called string.printable . You can use the random.sample function to pick out 8 from there:

import string
import random

result = random.sample(string.printable, 8)

result is now a list of 8 random printable characters.

I recommend using a generator. It will only work if you use python 2.5 or above.

from random import randint

def randnums(number, startnum=0, endnum=10):
    for i in range(1, number + 1):
        yield randint(startnum, endnum)

print list(randnums(8, endnum=100))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM