Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I implement a random.choice() like function which returns reproducible results?

I'd like to pass a fixed seed (string) to a function, and then have it randomly select one item from a list. However, it should be the same item from the same list if the same seed it used! Obviously this isn't random at all, but it should more or less appear to be random and be about equally distributed. It must be quite fast too.

To demonstrate, this is how random works.

>>> random.seed('Python')
>>> random.choice([1,2,3,4,5,6,7,8,9,0])
3
>>> random.choice([1,2,3,4,5,6,7,8,9,0])
6
>>> random.choice([1,2,3,4,5,6,7,8,9,0])
2

What I'd like is this.

>>> notrandom([1,2,3,4,5,6,7,8,9,0],seed='Python')
4
>>> notrandom([1,2,3,4,5,6,7,8,9,0],seed='Python')
4
>>> notrandom([1,2,3,4,5,6,7,8,9,0],seed='Python')
4

It only needs to be reproducible if the same list is used with the same seed string.


1 Answers

From the Python doc for random, I think this is what you are looking for:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

Like,

> r = random.Random()

> r.seed('Hi')
> r.random()
0.3787897089299177

> r.seed('Hi')
> r.random()
0.3787897089299177
like image 117
Owen Avatar answered Oct 20 '25 09:10

Owen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!