Gewoo
Gewoo

Reputation: 109

Python random number excluding one variable

Is it possible to create a variable with a random number except for one number that is stored in a variable?

For example:

import random
x = raw_input("Number: ")
y = random.randint(1,6)

So the variable x could never be y

Upvotes: 2

Views: 19442

Answers (6)

Martijn Pieters
Martijn Pieters

Reputation: 1122092

Rather than use random.randint(), produce a list of possible values and remove the one you don't want. Then use random.choice() on the reduced list:

import random
x = int(input("Number: "))
numbers = list(range(1, 7))
numbers.remove(x)
y = random.choice(numbers)

Demo:

>>> import random
>>> x = 5
>>> numbers = list(range(1, 7))
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> numbers.remove(x)
>>> numbers
[1, 2, 3, 4, 6]
>>> random.choice(numbers)
6
>>> random.choice(numbers)
1
>>> random.choice(numbers)
2

Upvotes: 4

Evalds Urtans
Evalds Urtans

Reputation: 6694

In python 3 to skip idx 11 from 0..20

import numpy as np
range = np.concatenate([np.arange(0, 10, dtype=np.int), np.arange(11, 20, dtype=np.int)])
choice = np.random.choice(range)

Upvotes: 0

Totem
Totem

Reputation: 7349

Try this:

import random

x = int(raw_input("Number(1-6): ")) # note I made x an int

while True:
    y = random.randint(1, 6)
    if x != y: break

Upvotes: 3

logic
logic

Reputation: 1727

As @jonrsharpe mentioned in the comments of your question, a simple while-loop would be the easiest way to achieve this:

import random
x = int(raw_input("Number: "))
y = random.randint(1,6)

while x == y:
    y=random.randint(1,6)

Upvotes: -1

rafaelc
rafaelc

Reputation: 59274

If you are sure X will be a number between 1 and 6, you can choose from range excluding X.

import random
x = input("Number: ")
end  = 6
r = range(1,x) + range(x+1, end)
random.choice(r)

Upvotes: 0

Abhijit
Abhijit

Reputation: 63737

I would suggest you to use random.choice form the list of numbers sans your number of choice

import random
x = raw_input("Number: ")
y = random.choice(range(1, x) + range(x+1, 6))

Upvotes: 5

Related Questions