Choosing random integers except for a particular number for python?
python, random
Solution
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]
Problem
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 ```