Reputation: 21
I have got a list like
L = ["bus", "bike"]
and I want to print randomly the items from the list
for i in range(10):
print "Customer %d uses the %s" % (i, random.choice(L))
If I want, for instance, to print "bus"
6 times and "bike"
4 times, is there a way to do it in Python?
Upvotes: 1
Views: 80
Reputation: 11302
To expand my comment slightly (and sorry for being a bit off-topic, since I'll not expound on Python, especially not random.choice()
here), you start from a "primitive", i.e. some random variable that can be generated readily, using various pseudo-random number generators.
Let's suppose that this primitive is the "uniform distibution on unit interval [0, 1]", and we denote this by X. [1]
What you need is a Bernoulli distribution with p = 0.6, i.e. among the two choices, one should be assigned probability 0.6, which implies the other given 0.4
There's a simple method, called the acceptance-rejection method for this. It is as simple as follows:
Generate a value x of X using the "primitive" PRNG;
Test whether this x is lower than 0.6:
If it is, output "bus"
Otherwise, output "bike"
End
This is an elementary example of the wide class of rejection methods. It is left as an exercise to see how this is related to (or in contrast with) the other answers suggested in this post (hint: how are they related to direct transformation method?).
[1] By the way, this can be done in Python by random.random()
.
Feel free to mod down for off-topic ;)
Upvotes: 0
Reputation: 955
import random
l = ['bus', 'bus', 'bus', 'bus', 'bus', 'bus', 'bike', 'bike', 'bike', 'bike']
for i in range(len(l)):
random.shuffle(l)
print l[0]
l.pop(0)
Upvotes: -1
Reputation: 117711
Create a list with your desired distribution and shuffle it:
l = 6*[0] + 4*[1]
random.shuffle(l)
for i in l:
print(L[i])
Upvotes: 3