Saturday 15 January 2011

python - Choosing items from a list on a percent basis -



python - Choosing items from a list on a percent basis -

i trying create programme using python takes names list, , displays names list in random order, while using each name once. have gotten far, , made work next code:

import random drivers = [ "john doe", "bill smith", "trent baxter", "ray olson", ] random.shuffle(drivers) position in drivers: print(position)

ouput:

bill smith john doe ray olson trent baxter

this works, have programme assign values each name create them more, or less picked, while still choosing each name once.

answer using standard modules:

from itertools import accumulate random import uniform class probitem(object): def __init__(self, value, prob): self.value = value self.prob = prob def pick(items): accum = list(accumulate(item.prob item in items)) rand = uniform(0, accum[-1]) i, prob in enumerate(accum): if rand < prob: homecoming items.pop(i).value drivers = [ probitem("john doe", 23.7), probitem("bill smith", 17), probitem("trent baxter", 12.43), probitem("ray olson", 9.99), ] while (drivers): print(pick(drivers))

depending on necessities, it's improve build generator...

python

No comments:

Post a Comment