蓄水池原理应用: 随机返回n个元素中的某个元素,从0开始遍历这n个元素 用count记录遍历过得元素数目(符合要求的元素在数,比如数值等于target的数组索引),如果random(count)==0 则选中这个元素。 可以证明 在遍历的过程中 随着遍历元素数目的增加 random(count)==0 的几率是随机均等的 Given an array of integers
# coding:utf8import random# 从n个数中采样k个数def reservoir_sampling(n, k):# 所有数据pool = [i for i in range(n)]# 前k个数据res = [i for i in range(k)]for i in range(k, n):v = random.randint(0, i)if v < k:res[v] =
小伙伴们中过奖么? 是不是都是 中奖绝缘体 呢? 今天我们就来聊一聊关于中奖的 概率 问题~ 先思考两个问题 如果让你从规模为 N 的数据序列中,随机选取出 k 个不重复的数据,你会怎么做呢? 是不是很简单,知道了总数 N ,等概率随机选择 k 个即可,每个数据被选到的概率均为 k / N k/N k/N 。 问题变一下:那如果从始至终都不知道 N 的具体大小呢?也就是说,数据流长度
蓄水池抽样问题是从动态变化的N个元素中随机抽选出M个元素(N>=M) 算法描述如下: Init : a reservoir with the size: kfor i= k+1 to NM=random(1, i);if( M < k)SWAP the Mth value and ith valueend for 由于N的个数是不确定的,这就意味着不论N的个数是多少,里面元素都要
问题起源于编程珠玑,其描述如下: How could you select one of n objects at random, where you see the objects sequentially but you do not know the value of n beforehand? For concreteness, how would you read a text