Reputation: 33
Ok so I am writing a code that generates a random number like this
import random
randomNumber = random.randrange(1,4)
How can I make Python print a number between that range of (1, 4) that WILL NEVER print the same number as the "random number" variable? For example say the randomNumber chooses the number 3. I want a second randomNumber picker to print either 1 or 2. How can I make this possible?
Upvotes: 1
Views: 112
Reputation: 6488
If you want to randomly return numbers in a certain range without ever repeating any number, you can use random.shuffle
as in unutbu's answer.
If you want to exclude only certain items (like just the first) from being repeated, you can use a set
and random.sample
:
x = set(range(1,4))
r = random.sample(x, 1)
x.remove(r) # we should never return r again
# these two calls might return the same number (but not r)
random.sample(x, 1)
random.sample(x, 1)
Responding to your comment:
My code is going to look like this randomNumber=random.randrange(1,4) userChoice=raw_input("Pick 1, 2, or 3") then I want to print the number that is not the same as userChoice or randomNumber. Lets call this variable "not"
Try:
randomNumber = random.randrange(1, 4)
userChoice = raw_input("Pick 1, 2, or 3")
s = set([1,2,3]) - set([randomNumber, userChoice])
notPicked = random.sample(s, 1)[0] # this returns a one-element list, so [0] gets that one value
Upvotes: 2
Reputation: 880079
To select k
items from the list, use random.sample:
import random
x = range(1,4)
print(random.sample(x, k))
If you want all the items from the range(1,4), shuffle it, and then just iterate through the shuffled list:
import random
x = list(range(1,4)) # list is for Python3 compatibility
random.shuffle(x)
print(x)
# [2, 3, 1]
Upvotes: 3
Reputation: 26582
If you want to obtain random values from a range and not repeating previous values, then you can use random.choice
on each iteration, then pop out the item from range and repeat again.
import random
seq = range(1, 4)
while len(seq) > 0:
ret = random.choice(seq)
seq.pop(seq.index(ret)) # pop result
print(ret)
Upvotes: 0