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='Pyth开发者_运维问答on')
4
It only needs to be reproducible if the same list is used with the same seed string.
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
First time, pick a random number from list, then hash the seed and save the pair in an array.
Afterwards, Hash seed and use it as a key in your array.
It's obviously a crappy solution but I think here it could do the trick.
Edit: just saw it's for same input list too. So hash the list and save that hash as well.
精彩评论