第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

隨機選擇的加權(quán)版本

隨機選擇的加權(quán)版本

達令說 2019-06-09 14:12:34
隨機選擇的加權(quán)版本我需要編寫隨機選擇的加權(quán)版本(列表中的每個元素被選中的概率不同)。這就是我想出來的: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這個功能對我來說太復(fù)雜了,太丑了。我希望在座的每一個人都能提出一些改進的建議,或者其他的方法。對我來說,效率并不像代碼的整潔和可讀性那么重要。
查看完整描述

3 回答

?
DIEA

TA貢獻1820條經(jīng)驗 獲得超2個贊

從1.7.0版本開始,NumPy有一個choice支持概率分布的函數(shù)。

from numpy.random import choice
draw = choice(list_of_candidates, number_of_items_to_pick,
              p=probability_distribution)

請注意probability_distribution是按同一順序排列的序列。list_of_candidates..您也可以使用關(guān)鍵字replace=False若要更改行為,使繪制的項不被替換,請執(zhí)行以下操作。


查看完整回答
反對 回復(fù) 2019-06-09
?
蠱毒傳說

TA貢獻1895條經(jīng)驗 獲得超3個贊

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"


查看完整回答
反對 回復(fù) 2019-06-09
  • 3 回答
  • 0 關(guān)注
  • 603 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號