defchoices(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.randomn=len(population)ifcum_weightsisNone:ifweightsisNone:floor=_floorn+=0.0# convert to float for a small speed improvementreturn[population[floor(random()*n)]foriin_repeat(None,k)]try:cum_weights=list(_accumulate(weights))exceptTypeError:ifnotisinstance(weights,int):raisek=weightsraiseTypeError(f'The number of choices must be a keyword argument: {k=}')fromNoneelifweightsisnotNone:raiseTypeError('Cannot specify both weights and cumulative weights')iflen(cum_weights)!=n:raiseValueError('The number of weights does not match the population')total=cum_weights[-1]+0.0# convert to floatiftotal<=0.0:raiseValueError('Total of weights must be greater than zero')ifnot_isfinite(total):raiseValueError('Total of weights must be finite')bisect=_bisecthi=n-1return[population[bisect(cum_weights,random()*total,0,hi)]foriin_repeat(None,k)]
defsample(self,population,k,*,counts=None):"""Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example: sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to: sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) """# Sampling without replacement entails tracking either potential# selections (the pool) in a list or previous selections in a set.# When the number of selections is small compared to the# population, then tracking selections is efficient, requiring# only a small set and an occasional reselection. For# a larger number of selections, the pool tracking method is# preferred since the list takes less space than the# set and it doesn't suffer from frequent reselections.# The number of calls to _randbelow() is kept at or near k, the# theoretical minimum. This is important because running time# is dominated by _randbelow() and because it extracts the# least entropy from the underlying random number generators.# Memory requirements are kept to the smaller of a k-length# set or an n-length list.# There are other sampling algorithms that do not require# auxiliary memory, but they were rejected because they made# too many calls to _randbelow(), making them slower and# causing them to eat more entropy than necessary.ifnotisinstance(population,_Sequence):raiseTypeError("Population must be a sequence. ""For dicts or sets, use sorted(d).")n=len(population)ifcountsisnotNone:cum_counts=list(_accumulate(counts))iflen(cum_counts)!=n:raiseValueError('The number of counts does not match the population')total=cum_counts.pop()ifnotisinstance(total,int):raiseTypeError('Counts must be integers')iftotal<=0:raiseValueError('Total of counts must be greater than zero')selections=self.sample(range(total),k=k)bisect=_bisectreturn[population[bisect(cum_counts,s)]forsinselections]randbelow=self._randbelowifnot0<=k<=n:raiseValueError("Sample larger than population or is negative")result=[None]*ksetsize=21# size of a small set minus size of an empty listifk>5:setsize+=4**_ceil(_log(k*3,4))# table size for big setsifn<=setsize:# An n-length list is smaller than a k-length set.# Invariant: non-selected at pool[0 : n-i]pool=list(population)foriinrange(k):j=randbelow(n-i)result[i]=pool[j]pool[j]=pool[n-i-1]# move non-selected item into vacancyelse:selected=set()selected_add=selected.addforiinrange(k):j=randbelow(n)whilejinselected:j=randbelow(n)selected_add(j)result[i]=population[j]returnresult