-2

For example, I need to choose three numbers from [-2,2] but with no duplicate, the following code can't accomplish this, I know I can do it by comparing the elements, but is there some elegant way to do so?

print(np.random.randint(-2,2,3))

Most general case is: choose m random numbers from range[a,b] with no duplicate.

an offer can't refuse
  • 4,245
  • 5
  • 30
  • 50

1 Answers1

3

Use the built-in random sample:

>>> import random
>>> random.sample(range(10), 5) # take 5 random elements from range(10)
[2, 4, 1, 7, 9]
Uriel
  • 15,579
  • 6
  • 25
  • 46