Python实现一个带权无回置随机抽选函数的方法


Posted in Python onJuly 24, 2019

需求

有一个抽奖应用,从所有参与的用户抽出K位中奖用户(K=奖品数量),且要根据每位用户拥有的抽奖码数量作为权重。

如假设有三个用户及他们的权重是: A(1), B(1), C(2)。希望抽到A的概率为25%,抽到B的概率为25%, 抽到C的概率为50%。

分析

比较直观的做法是把两个C放到列表中抽选,如[A, B, C, C], 使用Python内置的函数random.choice[A, B, C, C], 这样C抽到的概率即为50%。

这个办法的问题是权重比较大的时候,浪费内存空间。

更一般的方法是,将所有权重加和4,然后从[0, 4)区间里随机挑选一个值,将A, B, C占用不同大小的区间。[0,1)是A, [1,2)是B, [2,4)是C。

使用Python的函数random.ranint(0, 3)或者int(random.random()*4)均可产生0-3的随机整数R。判断R在哪个区间即选择哪个用户。

接下来是寻找随机数在哪个区间的方法,

一种方法是按顺序遍历列表并保存已遍历的元素权重综合S,一旦S大于R,就返回当前元素。

from operator import itemgetter

users = [('A', 1), ('B', 1), ('C', 2)]

total = sum(map(itemgetter(1), users))

rnd = int(random.random()*total) # 0~3

s = 0
for u, w in users:
  s += w
  if s > rnd:
   return u

不过这种方法的复杂度是O(N), 因为要遍历所有的users。

可以想到另外一种方法,先按顺序把累积加的权重排成列表,然后对它使用二分法搜索,二分法复杂度降到O(logN)(除去其他的处理)

users = [('A', 1), ('B', 1), ('C', 2)]

cum_weights = list(itertools.accumulate(map(itemgetter(1), users))) # [1, 2, 4]

total = cum_weights[-1]

rnd = int(random.random()*total) # 0~3

hi = len(cum_weights) - 1
index = bisect.bisect(cum_weights, rnd, 0, hi)

return users(index)[0]

Python内置库random的choices函数(3.6版本后有)即是如此实现,random.choices函数签名为 random.choices(population, weights=None, *, cum_weights=None, k=1) population是待选列表, weights是各自的权重,cum_weights是可选的计算好的累加权重(两者选一),k是抽选数量(有回置抽选)。 源码如下:

def choices(self, population, weights=None, *, cum_weights=None, k=1):
  """Return a k sized list of population elements chosen with replacement.
  If the relative weights or cumulative weights are not specified,
  the selections are made with equal probability.
  """
  random = self.random
  if cum_weights is None:
    if weights is None:
      _int = int
      total = len(population)
      return [population[_int(random() * total)] for i in range(k)]
    cum_weights = list(_itertools.accumulate(weights))
  elif weights is not None:
    raise TypeError('Cannot specify both weights and cumulative weights')
  if len(cum_weights) != len(population):
    raise ValueError('The number of weights does not match the population')
  bisect = _bisect.bisect
  total = cum_weights[-1]
  hi = len(cum_weights) - 1
  return [population[bisect(cum_weights, random() * total, 0, hi)]
      for i in range(k)]

更进一步

因为Python内置的random.choices是有回置抽选,无回置抽选函数是random.sample,但该函数不能根据权重抽选(random.sample(population, k))。

原生的random.sample可以抽选个多个元素但不影响原有的列表,其使用了两种算法实现, 保证了各种情况均有良好的性能。 (源码地址:random.sample)

第一种是部分shuffle,得到K个元素就返回。 时间复杂度是O(N),不过需要复制原有的序列,增加内存使用。

result = [None] * k
n = len(population)
pool = list(population) # 不改变原有的序列
for i in range(k):
  j = int(random.random()*(n-i))
  result[k] = pool[j]
  pool[j] = pool[n-i-1] # 已选中的元素移走,后面未选中元素填上
return result

而第二种是设置一个已选择的set,多次随机抽选,如果抽中的元素在set内,就重新再抽,无需复制新的序列。 当k相对n较小时,random.sample使用该算法,重复选择元素的概率较小。

selected = set()
selected_add = selected.add # 加速方法访问
for i in range(k):
  j = int(random.random()*n)
  while j in selected:
    j = int(random.random()*n)
  selected_add(j)
  result[j] = population[j]
return result

抽奖应用需要的是带权无回置抽选算法,结合random.choices和random.sample的实现写一个函数weighted_sample。

一般抽奖的人数都比奖品数量大得多,可选用random.sample的第二种方法作为无回置抽选,当然可以继续优化。

代码如下:

def weighted_sample(population, weights, k=1):
  """Like random.sample, but add weights.
  """
  n = len(population)
  if n == 0:
    return []
  if not 0 <= k <= n:
    raise ValueError("Sample larger than population or is negative")
  if len(weights) != n:
    raise ValueError('The number of weights does not match the population')

  cum_weights = list(itertools.accumulate(weights))
  total = cum_weights[-1]
  if total <= 0: # 预防一些错误的权重
    return random.sample(population, k=k)
  hi = len(cum_weights) - 1

  selected = set()
  _bisect = bisect.bisect
  _random = random.random
  selected_add = selected.add
  result = [None] * k
  for i in range(k):
    j = _bisect(cum_weights, _random()*total, 0, hi)
    while j in selected:
      j = _bisect(cum_weights, _random()*total, 0, hi)
    selected_add(j)
    result[i] = population[j]
  return result

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python with的用法
Aug 22 Python
python中base64加密解密方法实例分析
May 16 Python
浅析Python中元祖、列表和字典的区别
Aug 17 Python
Python3读取Excel数据存入MySQL的方法
May 04 Python
在Pycharm中自动添加时间日期作者等信息的方法
Jan 16 Python
pyqt5之将textBrowser的内容写入txt文档的方法
Jun 21 Python
Python的互斥锁与信号量详解
Sep 12 Python
Python 基于FIR实现Hilbert滤波器求信号包络详解
Feb 26 Python
通过Python实现一个简单的html页面
May 16 Python
selenium判断元素是否存在的两种方法小结
Dec 07 Python
Python利器openpyxl之操作excel表格
Apr 17 Python
Python OpenCV实现图像模板匹配详解
Apr 07 Python
Django的用户模块与权限系统的示例代码
Jul 24 #Python
python3字符串操作总结
Jul 24 #Python
django数据关系一对多、多对多模型、自关联的建立
Jul 24 #Python
django如何自己创建一个中间件
Jul 24 #Python
django如何通过类视图使用装饰器
Jul 24 #Python
django 类视图的使用方法详解
Jul 24 #Python
django如何实现视图重定向
Jul 24 #Python
You might like
重料打造自己的“宝马”---第三代
2021/03/02 无线电
PHP的面试题集,附我的答案和分析(一)
2006/11/19 PHP
PHP中simplexml_load_string函数使用说明
2011/01/01 PHP
PHP原生模板引擎 最简单的模板引擎
2012/04/25 PHP
PHP内核学习教程之php opcode内核实现
2016/01/27 PHP
ThinkPHP表单令牌错误的相关解决方法分析
2016/05/20 PHP
PHP校验15位和18位身份证号的类封装
2018/11/07 PHP
jQuery EasyUI 开源插件套装 完全替代ExtJS
2010/03/24 Javascript
validator验证控件使用代码
2010/11/23 Javascript
jQuery实现鼠标滚轮动态改变样式或效果
2015/01/05 Javascript
返回函数的JavaScript函数
2016/06/14 Javascript
AngularJS动态生成div的ID源码解析
2016/08/29 Javascript
详解AngularJS之$window窗口对象
2018/01/17 Javascript
微信小程序ibeacon三点定位详解
2018/10/31 Javascript
详解vue项目中实现图片裁剪功能
2019/06/07 Javascript
node.js使用zlib模块进行数据压缩和解压操作示例
2020/02/12 Javascript
[01:13:01]2018DOTA2亚洲邀请赛 4.4 淘汰赛 TNC vs VG 第三场
2018/04/05 DOTA
python append、extend与insert的区别
2016/10/13 Python
对python 数据处理中的LabelEncoder 和 OneHotEncoder详解
2018/07/11 Python
python实现简单的单变量线性回归方法
2018/11/08 Python
Python txt文件加入字典并查询的方法
2019/01/15 Python
python Pandas如何对数据集随机抽样
2019/07/29 Python
Python进程间通信multiprocess代码实例
2020/03/18 Python
详解python变量与数据类型
2020/08/25 Python
天巡全球:Skyscanner Global
2017/06/20 全球购物
Ruby如何实现动态方法调用
2012/11/18 面试题
应届大学生自荐信格式
2013/09/21 职场文书
领导检查欢迎词
2014/01/14 职场文书
幸福家庭事迹材料
2014/02/03 职场文书
母亲节感恩活动记录
2014/03/16 职场文书
女生抽烟检讨书
2014/10/05 职场文书
2015秋学期开学寄语
2015/05/28 职场文书
幼儿园班级管理心得体会
2016/01/07 职场文书
交通安全学习心得体会
2016/01/18 职场文书
解决Mysql多行子查询的使用及空值问题
2022/01/22 MySQL
基于Python实现nc批量转tif格式
2022/08/14 Python