Adon Bilivit
Adon Bilivit

Reputation: 26890

How to create a set of random numbers with numpy

My requirement is to create a set of random numbers. I know the set size and the random number range. Therefore:

import random
def makeset(lo, hi, ss):
  s = set()
  while len(s) < ss:
    s.add(random.randint(lo, hi))
  return s

I realise that certain combinations of lo, hi & ss could result in an impossible task but that's not in scope here.

I've started learning about numpy and wondered if that module offered something that could do this in a single step - i.e., no explicit loop.

But I can't find anything in the documentation. Maybe it's not there.

Any thoughts?

Upvotes: 1

Views: 211

Answers (2)

ansev
ansev

Reputation: 30920

We could use np.random.default_rng

Construct a new Generator with the default BitGenerator (PCG64)

import numpy as np
gen = np.random.default_rng()
def makeset(lo, hi, ss):
  return set(gen.choice(np.arange(lo, hi + 1), ss, replace=False))

Upvotes: 0

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

You could use np.random.choice without replacement as follows:

import numpy as np
gen = np.random.Generator(np.random.PCG64())
def with_numpy_gen(lo, hi, ss):
  return gen.choice(np.arange(lo, hi + 1), ss, replace=False)

Upvotes: 2

Related Questions