Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53850
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Subject | Re: Weighted choices |
| Date | 2013-09-08 20:21 -0400 |
| Organization | IISS Elusive Unicorn |
| References | <CANy1k1gHFFgd82P5VZJEEZvWe_kHJvi2r1uqVh3Sr=nFZyazuQ@mail.gmail.com> <522CB887.9090000@rece.vub.ac.be> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.160.1378686098.5461.python-list@python.org> (permalink) |
On Sun, 08 Sep 2013 19:48:55 +0200, Antoon Pardon
<antoon.pardon@rece.vub.ac.be> declaimed the following:
>Op 08-09-13 04:12, Jason Friedman schreef:
>> choices = dict()
>> choices["apple"] = 10
>> choices["pear"] = 20
>> choices["banana"] = 15
>> choices["orange"] = 25
>> choices["kiwi"] = 30
>>
>> I want to pick sets of fruit, three in a set, where the chance of
>> selecting a given fruit is proportional to its weight. In the example
>> above, pears should appear twice as often as apples and kiwis should
>> appear twice as often as bananas.
>
>Just a small question. Is a set of three bananas an acceptable outcome?
If we are talking probabilities, regardless of what the weighting is,
it should be probable (if unlikely) to get three-of-a-kind.
However, I would not use a dictionary for this. An ordered list should
work better... for small samples a list containing repeats (by weight) of
each choice, and then use a random integer whose range is 0..len(list)-1
would suffice.
choices = ["apple", "apple", "apple", ..., "kiwi", "kiwi" ]
For longer lists, storing a tuple with the accumulating weight, and
scanning from the beginning
choices = [(10, "Apple"), (10+20, "Pear"), (10+20+15, "Banana")... ]
generate random integer in the range of the sum of the weights, and accept
the last tuple whose first element is less than the integer. {Or convert
the weights to floating point (by dividing each by the total sum), same
concept but random number in range 0.0..1.0}
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Weighted choices Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-09-08 20:21 -0400
csiph-web