Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random.choice always same

Tags:

python

I have a quick question. I'm currently using random.choice() to pick from a list and was wondering why it always calls the same item. It changes once I stop the program and restart it. Could anyone explain to me how the random class works and makes it so it does this?

Thanks

like image 435
John Smith Avatar asked Apr 16 '12 21:04

John Smith


People also ask

What is random choice method?

Python Random choice() Method The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.

What is the difference between random choice and random choices?

The fundamental difference is that random. choices() will (eventually) draw elements at the same position (always sample from the entire sequence, so, once drawn, the elements are replaced - with replacement), while random.

How many arguments does random choice take?

random. choice() accepts one argument: the list from which you want to select an item. You may encounter a scenario where you want to choose an item randomly from a list.

Is NP random actually random?

Indeed, whenever we call a python function, such as np. random. rand() the output can only be deterministic and cannot be truly random. Hence, numpy has to come up with a trick to generate sequences of numbers that look like random and behave as if they came from a purely random source, and this is what PRNG are.


1 Answers

This is my guess as to what you are most likely doing:

import random

l = [1,2,3,4,5]
random.Random(500).choice(l)
# 4
random.Random(500).choice(l)
# 4
random.Random(500).choice(l)
# 4

If you are using the actual Random class with the same seed, and making a new instance each time, then you are performing the same pseudo random operation. This is actually a feature (seeding) to let you have a reproducible randomization in future runs of your routine.

Either do this with a seed:

l = [1,2,3,4,5]
r = random.Random(500) # seed number is arbitrary 
r.choice(l)
r.choice(l)

Or use the convenience method: random.choice(l)

like image 200
jdi Avatar answered Oct 01 '22 20:10

jdi