9 EYLÜL 2010, PERŞEMBE
Rastgele ağırlıklı bir sürüm.seçim
Rastgele ağırlıklı bir sürümü yazmak gerekiyordu.seçimi (listedeki her öğe seçilmek için farklı bir olasılık vardır). Bu ben ile geldi budur:
def weightedChoice(choices):
"""Like random.choice, but each element can have a different chance of
being selected.
choices can be any iterable containing iterables with two items each.
Technically, they can have more than two items, the rest will just be
ignored. The first item is the thing being chosen, the second item is
its weight. The weights can be any numeric values, what matters is the
relative differences between them.
"""
space = {}
current = 0
for choice, weight in choices:
if weight > 0:
space[current] = choice
current = weight
rand = random.uniform(0, current)
for key in sorted(space.keys() [current]):
if rand < key:
return choice
choice = space[key]
return None
Bu işlev, benim için aşırı karmaşık ve çirkin görünüyor. Herkes buranın iyileştirilmesi için bazı öneriler ya da bunu yapmanın başka yolları da teklif umuyorum. Verimliliği kod temizliği ve okunabilirlik gibi, bu benim için önemli değil.
CEVAP
9 EYLÜL 2010, PERŞEMBE
def weighted_choice(choices):
total = sum(w for c, w in choices)
r = random.uniform(0, total)
upto = 0
for c, w in choices:
if upto w > r:
return c
upto = w
assert False, "Shouldn't get here"
Bunu Paylaş:
Nasıl rastgele bir dizi seçim muyum?...
Django şablonları: bir seçim ayrıntılı...
Tüm yerel değişiklikler, sürüm bilgisi...
SQL Server: yanlış sürüm 661 Ekle...
MongoDB yollarını veriler sürüm uygula...