Pick items from list with probability based upon property of list member ?

southof40 shearichard at gmail.com
Mon Jun 21 05:58:42 EDT 2010


On Jun 20, 10:53 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Sun, 20 Jun 2010 03:19:55 -0700, southof40 wrote:
> > I have list of of N Vehicle objects - the only possible vehicles are
> > cars, bikes, trucks.
>
> > I want to select an object from the list with a probability of : cars
> > 0.7, bikes 0.3, trucks 0.1.
>
> That adds to a probability of 1.1, which is impossible.
>
> I'm going to assume that bikes is a typo and should be 0.2.
>
> cars = [car1, car2]
> bikes = [bike1, bike2, bike3, bike4, bike5, bike6]
> trucks = [truck1, truck2, truck3, truck4]
>
> x = random.random()
> if x < 0.7:
>     return random.choice(cars)
> elif x < 0.9:
>     return random.choice(bikes)
> else:
>     return random.choice(trucks)
>
> But surely this is not physically realistic? The probability of selecting
> a car would normally depend on the number of cars, and not be set before
> hand.
>
> --
> Steven

Nice solution thanks.



More information about the Python-list mailing list