You can use either of random.randint
or random.randrange
. So to get a random 3-digit number:
from random import randint, randrange
randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop
* Assuming you really meant three digits, rather than "up to three digits".
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
Use random.choice
on a list, but first remove that particular number from the list:
>>> import random
>>> n = 3
>>> end = 5
>>> r = list(range(1,n)) + list(range(n+1, end))
>>> r
[1, 2, 4]
>>> random.choice(r)
2
>>> random.choice(r)
4
Or define a function:
def func(n, end, start = 1):
return list(range(start, n)) + list(range(n+1, end))
...
>>> r = func(3, 5)
>>> r
[1, 2, 4]
>>> random.choice(r)
2
Update:
This returns all numbers other than a particular number from the list:
>>> r = range(5)
for player in r:
others = list(range(0, player)) + list(range(player+1, 5))
print player,'-->', others
...
0 --> [1, 2, 3, 4]
1 --> [0, 2, 3, 4]
2 --> [0, 1, 3, 4]
3 --> [0, 1, 2, 4]
4 --> [0, 1, 2, 3]
Best Answer
One way could be to define a list of odds from which to sample, but keeping in mind the how likely it should be for a number to be sampled randomly. Since there are ten times as many 2 digit numbers than 1 digit numbers, we need to set the weights of these sampling sizes according to this logic.
Following this reasoning, we could use
numpy.random.choice
, which allows for sampling from a list following a probability distribution:Let's check the generated distribution for
10_000
samples: