Python实现基于权重的随机数2种方法

WBOY
Release: 2016-06-06 11:26:03
Original
1300 people have browsed it

问题:

例如我们要选从不同省份选取一个号码,每个省份的权重不一样,直接选随机数肯定是不行的了,就需要一个模型来解决这个问题。
简化成下面的问题:

 字典的key代表是省份,value代表的是权重,我们现在需要一个函数,每次基于权重选择一个省份出来
{"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 
 
''''' 
每个元素都有权重,然后根据权重随机取值 
 
输入 {"A":2, "B":2, "C":4, "D":10, "E": 20} 
输出一个值 
''' 
import random 
import collections as coll 
 
data = {"A":2, "B":2, "C":4, "D":6, "E": 11} 
 
#第一种 根据元素权重值 "A"*2 ..等,把每个元素取权重个元素放到一个数组中,然后最数组下标取随机数得到权重 
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] 
  
#第二种 也是要计算出权重总和,取出一个随机数,遍历所有元素,把权重相加sum,当sum大于等于随机数字的时候停止,取出当前的元组 
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()") 
Copy after login

一次执行的结果

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

Copy after login


思路:

思路都很原始可以参考下面的连接,还有别的好方法一起交流!!
代码: https://gist.github.com/orangle/d83bec8984d0b4293710
参考:
http://www.bitsCN.com/article/65060.htm
http://www.bitsCN.com/article/65058.htm

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!