Reputation: 43
Is there a method in python to generate random non repeating numbers in a range except a specific number.For example i want to generate numbers between 1 and 10 but "1" should not be generated.Any help would be appreciated.Thanks.
Upvotes: 1
Views: 554
Reputation: 87064
Use random.sample()
with a population that does not include the value(s) that you don't like.
>>> import random
>>> population = range(2,11) # 2,3,4,5,6,7,8,9,10
>>> print random.sample(range(2,11), 5)
[6, 2, 4, 8, 9]
Or another example, if you don't want "42":
>>> population = range(1, 101) # 1,2,...,100
>>> population.remove(42)
>>> print random.sample(population, 20)
[45, 10, 86, 7, 79, 39, 88, 80, 41, 85, 25, 96, 68, 55, 5, 74, 8, 9, 65, 18]
Upvotes: 2
Reputation: 3288
Suppose you want to exclude n
in range of a
to b
import random
random.choice([random.randint(a,n-1),random.randint(n+1,b)])
Upvotes: 0