Generate random integers between 0 and 9
How can I generate random integers between 0 and 9 (inclusive) in Python?
For example, 0
, 1
, 2
, 3
, 4
, 开发者_JAVA百科5
, 6
, 7
, 8
, 9
Try random.randrange
:
from random import randrange
print(randrange(10))
Try random.randint
:
import random
print(random.randint(0, 9))
Docs state:
random.randint(a, b)
Return a random integer N such that a <= N <= b.
Try this:
from random import randrange, uniform
# randrange gives you an integral value
irand = randrange(0, 10)
# uniform gives you a floating-point value
frand = uniform(0, 10)
from random import randint
x = [randint(0, 9) for p in range(0, 10)]
This generates 10 pseudorandom integers in range 0 to 9 inclusive.
The secrets
module is new in Python 3.6. This is better than the random
module for cryptography or security uses.
To randomly print an integer in the inclusive range 0-9:
from secrets import randbelow
print(randbelow(10))
For details, see PEP 506.
Note that it really depends on the use case. With the random
module you can set a random seed, useful for pseudorandom but reproducible results, and this is not possible with the secrets
module.
random
module is also faster (tested on Python 3.9):
>>> timeit.timeit("random.randrange(10)", setup="import random")
0.4920286529999771
>>> timeit.timeit("secrets.randbelow(10)", setup="import secrets")
2.0670733770000425
I would try one of the following:
1.> numpy.random.randint
import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))
print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])
2.> numpy.random.uniform
import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)
print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])
3.> numpy.random.choice
import numpy as np
X3 = np.random.choice(a=10, size=15 )
print (X3)
>>> array([1, 4, 0, 2, 5, 2, 7, 5, 0, 0, 8, 4, 4, 0, 9])
4.> random.randrange
from random import randrange
X4 = [randrange(10) for i in range(15)]
print (X4)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]
5.> random.randint
from random import randint
X5 = [randint(0, 9) for i in range(0, 15)]
print (X5)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]
Speed:
► np.random.uniform and np.random.randint are much faster (~10 times faster) than np.random.choice, random.randrange, random.randint .
%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.random.choice(a=10, size=15 )
>> 21 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Notes:
1.> np.random.randint generates random integers over the half-open interval [low, high).
2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).
3.> np.random.choice generates a random sample over the half-open interval [low, high) as if the argument
a
was np.arange(n).4.> random.randrange(stop) generates a random number from range(start, stop, step).
5.> random.randint(a, b) returns a random integer N such that a <= N <= b.
6.> astype(int) casts the numpy array to int data type.
7.> I have chosen size = (15,). This will give you a numpy array of length = 15.
Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:
import numpy as np
np.random.randint(10, size=(1, 20))
You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).
array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])
While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):
How can I generate random integers between 0 and 9 (inclusive) in Python?
For clarity, here we demonstrate how to get multiple random integers.
Given
>>> import random
lo = 0
hi = 10
size = 5
Code
Multiple, Random Integers
# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]
# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]
# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]
# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]
# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]
Sample of Random Integers
# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]
# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]
Details
Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:
- A:
random.random
returns a random float in the range[0.0, 1.0)
- B:
random.randint
returns a random integerN
such thata <= N <= b
- C:
random.randrange
alias torandint(a, b+1)
- D:
random.shuffle
shuffles a sequence in place - E:
random.choice
returns a random element from the non-empty sequence - F:
random.choices
returnsk
selections from a population (with replacement, Python 3.6+) - G:
random.sample
returnsk
unique selections from a population (without replacement):2
See also R. Hettinger's talk on Chunking and Aliasing using examples from the random
module.
Here is a comparison of some random functions in the Standard Library and Numpy:
| | random | numpy.random |
|-|-----------------------|----------------------------------|
|A| random() | random() |
|B| randint(low, high) | randint(low, high) |
|C| randrange(low, high) | randint(low, high) |
|D| shuffle(seq) | shuffle(seq) |
|E| choice(seq) | choice(seq) |
|F| choices(seq, k) | choice(seq, size) |
|G| sample(seq, k) | choice(seq, size, replace=False) |
You can also quickly convert one of many distributions in Numpy to a sample of random integers.3
Examples
>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10, 3, 1, 16])
>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])
>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])
1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al. 2@prashanth mentions this module showing one integer. 3Demonstrated by @Siddharth Satpathy
You need the random
python module which is part of your standard library.
Use the code...
from random import randint
num1= randint(0,9)
This will set the variable num1
to a random number between 0
and 9
inclusive.
Try this through random.shuffle
>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
In case of continuous numbers randint
or randrange
are probably the best choices but if you have several distinct values in a sequence (i.e. a list
) you could also use choice
:
>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5
choice
also works for one item from a not-continuous sample:
>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7
If you need it "cryptographically strong" there's also a secrets.choice
in python 3.6 and newer:
>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
if you want to use numpy then use the following:
import numpy as np
print(np.random.randint(0,10))
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1
To get a list of ten samples:
>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
You can try importing the random module from Python and then making it choose a choice between the nine numbers. It's really basic.
import random
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can try putting the value the computer chose in a variable if you're going to use it later, but if not, the print function should work as such:
choice = random.choice(numbers)
print(choice)
Generating random integers between 0 and 9.
import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)
Output:
[4 8 0 4 9 6 9 9 0 7]
Best way is to use import Random function
import random
print(random.sample(range(10), 10))
or without any library import:
n={}
for i in range(10):
n[i]=i
for p in range(10):
print(n.popitem()[1])
here the popitems removes and returns an arbitrary value from the dictionary n
.
random.sample
is another that can be used
import random
n = 1 # specify the no. of numbers
num = random.sample(range(10), n)
num[0] # is the required number
This is more of a mathematical approach but it works 100% of the time:
Let's say you want to use random.random()
function to generate a number between a
and b
. To achieve this, just do the following:
num = (b-a)*random.random() + a;
Of course, you can generate more numbers.
From the documentation page for the random module:
Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.
random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.
>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'
Instead of string.digits
, range
could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.
I thought I'd add to these answers with quantumrand
, which uses ANU's quantum number generator. Unfortunately this requires an internet connection, but if you're concerned with "how random" the numbers are then this could be useful.
https://pypi.org/project/quantumrand/
Example
import quantumrand
number = quantumrand.randint(0, 9)
print(number)
Output: 4
The docs have a lot of different examples including dice rolls and a list picker.
I had better luck with this for Python 3.6
str_Key = ""
str_RandomKey = ""
for int_I in range(128):
str_Key = random.choice('0123456789')
str_RandomKey = str_RandomKey + str_Key
Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.
OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined
defined class.
The following simulates 12 outcomes of the distribution.
import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
x = distribution.getRealization()
print(i,x)
This prints:
0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]
The brackets are there becausex
is a Point
in 1-dimension.
It would be easier to generate the 12 outcomes in a single call to getSample
:
sample = distribution.getSample(12)
would produce:
>>> print(sample)
[ v0 ]
0 : [ 3 ]
1 : [ 9 ]
2 : [ 6 ]
3 : [ 3 ]
4 : [ 2 ]
5 : [ 6 ]
6 : [ 9 ]
7 : [ 5 ]
8 : [ 9 ]
9 : [ 5 ]
10 : [ 3 ]
11 : [ 2 ]
More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html
精彩评论