欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)基于權(quán)重的隨機(jī)數(shù)2種方法

 更新時(shí)間:2015年04月28日 09:57:17   投稿:junjie  
這篇文章主要介紹了Python實(shí)現(xiàn)基于權(quán)重的隨機(jī)數(shù)2種方法,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下

問題:

例如我們要選從不同省份選取一個(gè)號(hào)碼,每個(gè)省份的權(quán)重不一樣,直接選隨機(jī)數(shù)肯定是不行的了,就需要一個(gè)模型來解決這個(gè)問題。
簡化成下面的問題:

 字典的key代表是省份,value代表的是權(quán)重,我們現(xiàn)在需要一個(gè)函數(shù),每次基于權(quán)重選擇一個(gè)省份出來
{"A":2, "B":2, "C":4, "D":10, "E": 20}

解決:

這是能想到和能看到的最多的版本,不知道還沒有更高效好用的算法。

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
#python2.7x 
#random_weight.py 
#author: orangleliu@gmail.com 2014-10-11 
 
''''' 
每個(gè)元素都有權(quán)重,然后根據(jù)權(quán)重隨機(jī)取值 
 
輸入 {"A":2, "B":2, "C":4, "D":10, "E": 20} 
輸出一個(gè)值 
''' 
import random 
import collections as coll 
 
data = {"A":2, "B":2, "C":4, "D":6, "E": 11} 
 
#第一種 根據(jù)元素權(quán)重值 "A"*2 ..等,把每個(gè)元素取權(quán)重個(gè)元素放到一個(gè)數(shù)組中,然后最數(shù)組下標(biāo)取隨機(jī)數(shù)得到權(quán)重 
def list_method(): 
 all_data = [] 
 for v, w in data.items(): 
  temp = [] 
  for i in range(w): 
   temp.append(v) 
  all_data.extend(temp) 
   
 n = random.randint(0,len(all_data)-1) 
 return all_data[n] 
  
#第二種 也是要計(jì)算出權(quán)重總和,取出一個(gè)隨機(jī)數(shù),遍歷所有元素,把權(quán)重相加sum,當(dāng)sum大于等于隨機(jī)數(shù)字的時(shí)候停止,取出當(dāng)前的元組 
def iter_method(): 
 total = sum(data.values()) 
 rad = random.randint(1,total) 
  
 cur_total = 0 
 res = "" 
 for k, v in data.items(): 
  cur_total += v 
  if rad<= cur_total: 
   res = k 
   break 
 return res 
  
  
def test(method): 
 dict_num = coll.defaultdict(int) 
 for i in range(100): 
  dict_num[eval(method)] += 1 
 for i,j in dict_num.items(): 
  print i, j  
  
if __name__ == "__main__": 
 test("list_method()") 
 print "-"*50 
 test("iter_method()") 

一次執(zhí)行的結(jié)果

A 4 
C 14 
B 7 
E 44 
D 31 
-------------------------------------------------- 
A 8 
C 16 
B 6 
E 43 
D 27 


思路:

思路都很原始可以參考下面的連接,還有別的好方法一起交流?。?br /> 代碼: https://gist.github.com/orangle/d83bec8984d0b4293710
參考:
http://www.dbjr.com.cn/article/65060.htm
http://www.dbjr.com.cn/article/65058.htm

相關(guān)文章

最新評(píng)論