Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing random integers except for a particular number for python?

Tags:

python

random

I am just wondering how do I make python generate random numbers other than a particular number? For instance, I want it to generate any number from 1 to 5 except 3, so the output would be 1, 2, 4, 5 and 3 will not be counted in the list. What can I do to achieve that?

An example would be like this:
There are five computerized players (Player 0 to 4) in a game.
Player 1 randomly selects one other player (except itself) and Player 2 to 4 will do the same thing.

So the output will be something like:

Player 1, who do you want to play with?
Player 1 chooses Player 2
like image 620
bugbytes Avatar asked Jul 28 '13 10:07

bugbytes


People also ask

How do you exclude numbers in a range in Python?

If you want to exclude 0 then change your range to (1,11). The way range works is the lower limit is inclusive where as upper limit is exclusive. On an unrelated note, if your lower limit is 0, you need not include the lower limit and write it as range(11) which is same as range(0,11).

How do you make Python choose a random number from a list?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.


1 Answers

While other answers are correct. The use of intermediate lists is inefficient.


Alternate Solution: Another way you could do this is by choosing randomly from a range of numbers that is n-1 in size. Then adding +1 to any results that are greater than or equal to >= the number you want to skip.

The following function random_choice_except implements the same API as np.random.choice, and so adjusting size allows efficient generation of multiple random values:


import numpy as np

def random_choice_except(a: int, excluding: int, size=None, replace=True):
    # generate random values in the range [0, a-1)
    choices = np.random.choice(a-1, size, replace=replace)
    # shift values to avoid the excluded number
    return choices + (choices >= excluding)

random_choice_except(3, 1)
# >>> 0  <or>  2  
random_choice_except(3, 1, size=10)
# >>> eg. [0 2 0 0 0 2 2 0 0 2]

The behaviour of np.random.choice changes depending on if an integer, list or array is passed as an argument. To prevent unwanted behavior we may want to add the following assertion at the top of the function: assert isinstance(a, int)

like image 153
Nathan Avatar answered Sep 29 '22 01:09

Nathan