Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: random.py
"""Random variable generators.
[0] Fix | Delete
[1] Fix | Delete
bytes
[2] Fix | Delete
-----
[3] Fix | Delete
uniform bytes (values between 0 and 255)
[4] Fix | Delete
[5] Fix | Delete
integers
[6] Fix | Delete
--------
[7] Fix | Delete
uniform within range
[8] Fix | Delete
[9] Fix | Delete
sequences
[10] Fix | Delete
---------
[11] Fix | Delete
pick random element
[12] Fix | Delete
pick random sample
[13] Fix | Delete
pick weighted random sample
[14] Fix | Delete
generate random permutation
[15] Fix | Delete
[16] Fix | Delete
distributions on the real line:
[17] Fix | Delete
------------------------------
[18] Fix | Delete
uniform
[19] Fix | Delete
triangular
[20] Fix | Delete
normal (Gaussian)
[21] Fix | Delete
lognormal
[22] Fix | Delete
negative exponential
[23] Fix | Delete
gamma
[24] Fix | Delete
beta
[25] Fix | Delete
pareto
[26] Fix | Delete
Weibull
[27] Fix | Delete
[28] Fix | Delete
distributions on the circle (angles 0 to 2pi)
[29] Fix | Delete
---------------------------------------------
[30] Fix | Delete
circular uniform
[31] Fix | Delete
von Mises
[32] Fix | Delete
[33] Fix | Delete
General notes on the underlying Mersenne Twister core generator:
[34] Fix | Delete
[35] Fix | Delete
* The period is 2**19937-1.
[36] Fix | Delete
* It is one of the most extensively tested generators in existence.
[37] Fix | Delete
* The random() method is implemented in C, executes in a single Python step,
[38] Fix | Delete
and is, therefore, threadsafe.
[39] Fix | Delete
[40] Fix | Delete
"""
[41] Fix | Delete
[42] Fix | Delete
# Translated by Guido van Rossum from C source provided by
[43] Fix | Delete
# Adrian Baddeley. Adapted by Raymond Hettinger for use with
[44] Fix | Delete
# the Mersenne Twister and os.urandom() core generators.
[45] Fix | Delete
[46] Fix | Delete
from warnings import warn as _warn
[47] Fix | Delete
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
[48] Fix | Delete
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
[49] Fix | Delete
from math import tau as TWOPI, floor as _floor
[50] Fix | Delete
from os import urandom as _urandom
[51] Fix | Delete
from _collections_abc import Set as _Set, Sequence as _Sequence
[52] Fix | Delete
from itertools import accumulate as _accumulate, repeat as _repeat
[53] Fix | Delete
from bisect import bisect as _bisect
[54] Fix | Delete
import os as _os
[55] Fix | Delete
import _random
[56] Fix | Delete
[57] Fix | Delete
try:
[58] Fix | Delete
# hashlib is pretty heavy to load, try lean internal module first
[59] Fix | Delete
from _sha512 import sha512 as _sha512
[60] Fix | Delete
except ImportError:
[61] Fix | Delete
# fallback to official implementation
[62] Fix | Delete
from hashlib import sha512 as _sha512
[63] Fix | Delete
[64] Fix | Delete
__all__ = [
[65] Fix | Delete
"Random",
[66] Fix | Delete
"SystemRandom",
[67] Fix | Delete
"betavariate",
[68] Fix | Delete
"choice",
[69] Fix | Delete
"choices",
[70] Fix | Delete
"expovariate",
[71] Fix | Delete
"gammavariate",
[72] Fix | Delete
"gauss",
[73] Fix | Delete
"getrandbits",
[74] Fix | Delete
"getstate",
[75] Fix | Delete
"lognormvariate",
[76] Fix | Delete
"normalvariate",
[77] Fix | Delete
"paretovariate",
[78] Fix | Delete
"randbytes",
[79] Fix | Delete
"randint",
[80] Fix | Delete
"random",
[81] Fix | Delete
"randrange",
[82] Fix | Delete
"sample",
[83] Fix | Delete
"seed",
[84] Fix | Delete
"setstate",
[85] Fix | Delete
"shuffle",
[86] Fix | Delete
"triangular",
[87] Fix | Delete
"uniform",
[88] Fix | Delete
"vonmisesvariate",
[89] Fix | Delete
"weibullvariate",
[90] Fix | Delete
]
[91] Fix | Delete
[92] Fix | Delete
NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0)
[93] Fix | Delete
LOG4 = _log(4.0)
[94] Fix | Delete
SG_MAGICCONST = 1.0 + _log(4.5)
[95] Fix | Delete
BPF = 53 # Number of bits in a float
[96] Fix | Delete
RECIP_BPF = 2 ** -BPF
[97] Fix | Delete
[98] Fix | Delete
[99] Fix | Delete
class Random(_random.Random):
[100] Fix | Delete
"""Random number generator base class used by bound module functions.
[101] Fix | Delete
[102] Fix | Delete
Used to instantiate instances of Random to get generators that don't
[103] Fix | Delete
share state.
[104] Fix | Delete
[105] Fix | Delete
Class Random can also be subclassed if you want to use a different basic
[106] Fix | Delete
generator of your own devising: in that case, override the following
[107] Fix | Delete
methods: random(), seed(), getstate(), and setstate().
[108] Fix | Delete
Optionally, implement a getrandbits() method so that randrange()
[109] Fix | Delete
can cover arbitrarily large ranges.
[110] Fix | Delete
[111] Fix | Delete
"""
[112] Fix | Delete
[113] Fix | Delete
VERSION = 3 # used by getstate/setstate
[114] Fix | Delete
[115] Fix | Delete
def __init__(self, x=None):
[116] Fix | Delete
"""Initialize an instance.
[117] Fix | Delete
[118] Fix | Delete
Optional argument x controls seeding, as for Random.seed().
[119] Fix | Delete
"""
[120] Fix | Delete
[121] Fix | Delete
self.seed(x)
[122] Fix | Delete
self.gauss_next = None
[123] Fix | Delete
[124] Fix | Delete
def seed(self, a=None, version=2):
[125] Fix | Delete
"""Initialize internal state from a seed.
[126] Fix | Delete
[127] Fix | Delete
The only supported seed types are None, int, float,
[128] Fix | Delete
str, bytes, and bytearray.
[129] Fix | Delete
[130] Fix | Delete
None or no argument seeds from current time or from an operating
[131] Fix | Delete
system specific randomness source if available.
[132] Fix | Delete
[133] Fix | Delete
If *a* is an int, all bits are used.
[134] Fix | Delete
[135] Fix | Delete
For version 2 (the default), all of the bits are used if *a* is a str,
[136] Fix | Delete
bytes, or bytearray. For version 1 (provided for reproducing random
[137] Fix | Delete
sequences from older versions of Python), the algorithm for str and
[138] Fix | Delete
bytes generates a narrower range of seeds.
[139] Fix | Delete
[140] Fix | Delete
"""
[141] Fix | Delete
[142] Fix | Delete
if version == 1 and isinstance(a, (str, bytes)):
[143] Fix | Delete
a = a.decode('latin-1') if isinstance(a, bytes) else a
[144] Fix | Delete
x = ord(a[0]) << 7 if a else 0
[145] Fix | Delete
for c in map(ord, a):
[146] Fix | Delete
x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF
[147] Fix | Delete
x ^= len(a)
[148] Fix | Delete
a = -2 if x == -1 else x
[149] Fix | Delete
[150] Fix | Delete
elif version == 2 and isinstance(a, (str, bytes, bytearray)):
[151] Fix | Delete
if isinstance(a, str):
[152] Fix | Delete
a = a.encode()
[153] Fix | Delete
a = int.from_bytes(a + _sha512(a).digest(), 'big')
[154] Fix | Delete
[155] Fix | Delete
elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
[156] Fix | Delete
_warn('Seeding based on hashing is deprecated\n'
[157] Fix | Delete
'since Python 3.9 and will be removed in a subsequent '
[158] Fix | Delete
'version. The only \n'
[159] Fix | Delete
'supported seed types are: None, '
[160] Fix | Delete
'int, float, str, bytes, and bytearray.',
[161] Fix | Delete
DeprecationWarning, 2)
[162] Fix | Delete
[163] Fix | Delete
super().seed(a)
[164] Fix | Delete
self.gauss_next = None
[165] Fix | Delete
[166] Fix | Delete
def getstate(self):
[167] Fix | Delete
"""Return internal state; can be passed to setstate() later."""
[168] Fix | Delete
return self.VERSION, super().getstate(), self.gauss_next
[169] Fix | Delete
[170] Fix | Delete
def setstate(self, state):
[171] Fix | Delete
"""Restore internal state from object returned by getstate()."""
[172] Fix | Delete
version = state[0]
[173] Fix | Delete
if version == 3:
[174] Fix | Delete
version, internalstate, self.gauss_next = state
[175] Fix | Delete
super().setstate(internalstate)
[176] Fix | Delete
elif version == 2:
[177] Fix | Delete
version, internalstate, self.gauss_next = state
[178] Fix | Delete
# In version 2, the state was saved as signed ints, which causes
[179] Fix | Delete
# inconsistencies between 32/64-bit systems. The state is
[180] Fix | Delete
# really unsigned 32-bit ints, so we convert negative ints from
[181] Fix | Delete
# version 2 to positive longs for version 3.
[182] Fix | Delete
try:
[183] Fix | Delete
internalstate = tuple(x % (2 ** 32) for x in internalstate)
[184] Fix | Delete
except ValueError as e:
[185] Fix | Delete
raise TypeError from e
[186] Fix | Delete
super().setstate(internalstate)
[187] Fix | Delete
else:
[188] Fix | Delete
raise ValueError("state with version %s passed to "
[189] Fix | Delete
"Random.setstate() of version %s" %
[190] Fix | Delete
(version, self.VERSION))
[191] Fix | Delete
[192] Fix | Delete
[193] Fix | Delete
## -------------------------------------------------------
[194] Fix | Delete
## ---- Methods below this point do not need to be overridden or extended
[195] Fix | Delete
## ---- when subclassing for the purpose of using a different core generator.
[196] Fix | Delete
[197] Fix | Delete
[198] Fix | Delete
## -------------------- pickle support -------------------
[199] Fix | Delete
[200] Fix | Delete
# Issue 17489: Since __reduce__ was defined to fix #759889 this is no
[201] Fix | Delete
# longer called; we leave it here because it has been here since random was
[202] Fix | Delete
# rewritten back in 2001 and why risk breaking something.
[203] Fix | Delete
def __getstate__(self): # for pickle
[204] Fix | Delete
return self.getstate()
[205] Fix | Delete
[206] Fix | Delete
def __setstate__(self, state): # for pickle
[207] Fix | Delete
self.setstate(state)
[208] Fix | Delete
[209] Fix | Delete
def __reduce__(self):
[210] Fix | Delete
return self.__class__, (), self.getstate()
[211] Fix | Delete
[212] Fix | Delete
[213] Fix | Delete
## ---- internal support method for evenly distributed integers ----
[214] Fix | Delete
[215] Fix | Delete
def __init_subclass__(cls, /, **kwargs):
[216] Fix | Delete
"""Control how subclasses generate random integers.
[217] Fix | Delete
[218] Fix | Delete
The algorithm a subclass can use depends on the random() and/or
[219] Fix | Delete
getrandbits() implementation available to it and determines
[220] Fix | Delete
whether it can generate random integers from arbitrarily large
[221] Fix | Delete
ranges.
[222] Fix | Delete
"""
[223] Fix | Delete
[224] Fix | Delete
for c in cls.__mro__:
[225] Fix | Delete
if '_randbelow' in c.__dict__:
[226] Fix | Delete
# just inherit it
[227] Fix | Delete
break
[228] Fix | Delete
if 'getrandbits' in c.__dict__:
[229] Fix | Delete
cls._randbelow = cls._randbelow_with_getrandbits
[230] Fix | Delete
break
[231] Fix | Delete
if 'random' in c.__dict__:
[232] Fix | Delete
cls._randbelow = cls._randbelow_without_getrandbits
[233] Fix | Delete
break
[234] Fix | Delete
[235] Fix | Delete
def _randbelow_with_getrandbits(self, n):
[236] Fix | Delete
"Return a random int in the range [0,n). Returns 0 if n==0."
[237] Fix | Delete
[238] Fix | Delete
if not n:
[239] Fix | Delete
return 0
[240] Fix | Delete
getrandbits = self.getrandbits
[241] Fix | Delete
k = n.bit_length() # don't use (n-1) here because n can be 1
[242] Fix | Delete
r = getrandbits(k) # 0 <= r < 2**k
[243] Fix | Delete
while r >= n:
[244] Fix | Delete
r = getrandbits(k)
[245] Fix | Delete
return r
[246] Fix | Delete
[247] Fix | Delete
def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF):
[248] Fix | Delete
"""Return a random int in the range [0,n). Returns 0 if n==0.
[249] Fix | Delete
[250] Fix | Delete
The implementation does not use getrandbits, but only random.
[251] Fix | Delete
"""
[252] Fix | Delete
[253] Fix | Delete
random = self.random
[254] Fix | Delete
if n >= maxsize:
[255] Fix | Delete
_warn("Underlying random() generator does not supply \n"
[256] Fix | Delete
"enough bits to choose from a population range this large.\n"
[257] Fix | Delete
"To remove the range limitation, add a getrandbits() method.")
[258] Fix | Delete
return _floor(random() * n)
[259] Fix | Delete
if n == 0:
[260] Fix | Delete
return 0
[261] Fix | Delete
rem = maxsize % n
[262] Fix | Delete
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
[263] Fix | Delete
r = random()
[264] Fix | Delete
while r >= limit:
[265] Fix | Delete
r = random()
[266] Fix | Delete
return _floor(r * maxsize) % n
[267] Fix | Delete
[268] Fix | Delete
_randbelow = _randbelow_with_getrandbits
[269] Fix | Delete
[270] Fix | Delete
[271] Fix | Delete
## --------------------------------------------------------
[272] Fix | Delete
## ---- Methods below this point generate custom distributions
[273] Fix | Delete
## ---- based on the methods defined above. They do not
[274] Fix | Delete
## ---- directly touch the underlying generator and only
[275] Fix | Delete
## ---- access randomness through the methods: random(),
[276] Fix | Delete
## ---- getrandbits(), or _randbelow().
[277] Fix | Delete
[278] Fix | Delete
[279] Fix | Delete
## -------------------- bytes methods ---------------------
[280] Fix | Delete
[281] Fix | Delete
def randbytes(self, n):
[282] Fix | Delete
"""Generate n random bytes."""
[283] Fix | Delete
return self.getrandbits(n * 8).to_bytes(n, 'little')
[284] Fix | Delete
[285] Fix | Delete
[286] Fix | Delete
## -------------------- integer methods -------------------
[287] Fix | Delete
[288] Fix | Delete
def randrange(self, start, stop=None, step=1):
[289] Fix | Delete
"""Choose a random item from range(start, stop[, step]).
[290] Fix | Delete
[291] Fix | Delete
This fixes the problem with randint() which includes the
[292] Fix | Delete
endpoint; in Python this is usually not what you want.
[293] Fix | Delete
[294] Fix | Delete
"""
[295] Fix | Delete
[296] Fix | Delete
# This code is a bit messy to make it fast for the
[297] Fix | Delete
# common case while still doing adequate error checking.
[298] Fix | Delete
istart = int(start)
[299] Fix | Delete
if istart != start:
[300] Fix | Delete
raise ValueError("non-integer arg 1 for randrange()")
[301] Fix | Delete
if stop is None:
[302] Fix | Delete
if istart > 0:
[303] Fix | Delete
return self._randbelow(istart)
[304] Fix | Delete
raise ValueError("empty range for randrange()")
[305] Fix | Delete
[306] Fix | Delete
# stop argument supplied.
[307] Fix | Delete
istop = int(stop)
[308] Fix | Delete
if istop != stop:
[309] Fix | Delete
raise ValueError("non-integer stop for randrange()")
[310] Fix | Delete
width = istop - istart
[311] Fix | Delete
if step == 1 and width > 0:
[312] Fix | Delete
return istart + self._randbelow(width)
[313] Fix | Delete
if step == 1:
[314] Fix | Delete
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
[315] Fix | Delete
[316] Fix | Delete
# Non-unit step argument supplied.
[317] Fix | Delete
istep = int(step)
[318] Fix | Delete
if istep != step:
[319] Fix | Delete
raise ValueError("non-integer step for randrange()")
[320] Fix | Delete
if istep > 0:
[321] Fix | Delete
n = (width + istep - 1) // istep
[322] Fix | Delete
elif istep < 0:
[323] Fix | Delete
n = (width + istep + 1) // istep
[324] Fix | Delete
else:
[325] Fix | Delete
raise ValueError("zero step for randrange()")
[326] Fix | Delete
[327] Fix | Delete
if n <= 0:
[328] Fix | Delete
raise ValueError("empty range for randrange()")
[329] Fix | Delete
[330] Fix | Delete
return istart + istep * self._randbelow(n)
[331] Fix | Delete
[332] Fix | Delete
def randint(self, a, b):
[333] Fix | Delete
"""Return random integer in range [a, b], including both end points.
[334] Fix | Delete
"""
[335] Fix | Delete
[336] Fix | Delete
return self.randrange(a, b+1)
[337] Fix | Delete
[338] Fix | Delete
[339] Fix | Delete
## -------------------- sequence methods -------------------
[340] Fix | Delete
[341] Fix | Delete
def choice(self, seq):
[342] Fix | Delete
"""Choose a random element from a non-empty sequence."""
[343] Fix | Delete
# raises IndexError if seq is empty
[344] Fix | Delete
return seq[self._randbelow(len(seq))]
[345] Fix | Delete
[346] Fix | Delete
def shuffle(self, x, random=None):
[347] Fix | Delete
"""Shuffle list x in place, and return None.
[348] Fix | Delete
[349] Fix | Delete
Optional argument random is a 0-argument function returning a
[350] Fix | Delete
random float in [0.0, 1.0); if it is the default None, the
[351] Fix | Delete
standard random.random will be used.
[352] Fix | Delete
[353] Fix | Delete
"""
[354] Fix | Delete
[355] Fix | Delete
if random is None:
[356] Fix | Delete
randbelow = self._randbelow
[357] Fix | Delete
for i in reversed(range(1, len(x))):
[358] Fix | Delete
# pick an element in x[:i+1] with which to exchange x[i]
[359] Fix | Delete
j = randbelow(i + 1)
[360] Fix | Delete
x[i], x[j] = x[j], x[i]
[361] Fix | Delete
else:
[362] Fix | Delete
_warn('The *random* parameter to shuffle() has been deprecated\n'
[363] Fix | Delete
'since Python 3.9 and will be removed in a subsequent '
[364] Fix | Delete
'version.',
[365] Fix | Delete
DeprecationWarning, 2)
[366] Fix | Delete
floor = _floor
[367] Fix | Delete
for i in reversed(range(1, len(x))):
[368] Fix | Delete
# pick an element in x[:i+1] with which to exchange x[i]
[369] Fix | Delete
j = floor(random() * (i + 1))
[370] Fix | Delete
x[i], x[j] = x[j], x[i]
[371] Fix | Delete
[372] Fix | Delete
def sample(self, population, k, *, counts=None):
[373] Fix | Delete
"""Chooses k unique random elements from a population sequence or set.
[374] Fix | Delete
[375] Fix | Delete
Returns a new list containing elements from the population while
[376] Fix | Delete
leaving the original population unchanged. The resulting list is
[377] Fix | Delete
in selection order so that all sub-slices will also be valid random
[378] Fix | Delete
samples. This allows raffle winners (the sample) to be partitioned
[379] Fix | Delete
into grand prize and second place winners (the subslices).
[380] Fix | Delete
[381] Fix | Delete
Members of the population need not be hashable or unique. If the
[382] Fix | Delete
population contains repeats, then each occurrence is a possible
[383] Fix | Delete
selection in the sample.
[384] Fix | Delete
[385] Fix | Delete
Repeated elements can be specified one at a time or with the optional
[386] Fix | Delete
counts parameter. For example:
[387] Fix | Delete
[388] Fix | Delete
sample(['red', 'blue'], counts=[4, 2], k=5)
[389] Fix | Delete
[390] Fix | Delete
is equivalent to:
[391] Fix | Delete
[392] Fix | Delete
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
[393] Fix | Delete
[394] Fix | Delete
To choose a sample from a range of integers, use range() for the
[395] Fix | Delete
population argument. This is especially fast and space efficient
[396] Fix | Delete
for sampling from a large population:
[397] Fix | Delete
[398] Fix | Delete
sample(range(10000000), 60)
[399] Fix | Delete
[400] Fix | Delete
"""
[401] Fix | Delete
[402] Fix | Delete
# Sampling without replacement entails tracking either potential
[403] Fix | Delete
# selections (the pool) in a list or previous selections in a set.
[404] Fix | Delete
[405] Fix | Delete
# When the number of selections is small compared to the
[406] Fix | Delete
# population, then tracking selections is efficient, requiring
[407] Fix | Delete
# only a small set and an occasional reselection. For
[408] Fix | Delete
# a larger number of selections, the pool tracking method is
[409] Fix | Delete
# preferred since the list takes less space than the
[410] Fix | Delete
# set and it doesn't suffer from frequent reselections.
[411] Fix | Delete
[412] Fix | Delete
# The number of calls to _randbelow() is kept at or near k, the
[413] Fix | Delete
# theoretical minimum. This is important because running time
[414] Fix | Delete
# is dominated by _randbelow() and because it extracts the
[415] Fix | Delete
# least entropy from the underlying random number generators.
[416] Fix | Delete
[417] Fix | Delete
# Memory requirements are kept to the smaller of a k-length
[418] Fix | Delete
# set or an n-length list.
[419] Fix | Delete
[420] Fix | Delete
# There are other sampling algorithms that do not require
[421] Fix | Delete
# auxiliary memory, but they were rejected because they made
[422] Fix | Delete
# too many calls to _randbelow(), making them slower and
[423] Fix | Delete
# causing them to eat more entropy than necessary.
[424] Fix | Delete
[425] Fix | Delete
if isinstance(population, _Set):
[426] Fix | Delete
_warn('Sampling from a set deprecated\n'
[427] Fix | Delete
'since Python 3.9 and will be removed in a subsequent version.',
[428] Fix | Delete
DeprecationWarning, 2)
[429] Fix | Delete
population = tuple(population)
[430] Fix | Delete
if not isinstance(population, _Sequence):
[431] Fix | Delete
raise TypeError("Population must be a sequence. For dicts or sets, use sorted(d).")
[432] Fix | Delete
n = len(population)
[433] Fix | Delete
if counts is not None:
[434] Fix | Delete
cum_counts = list(_accumulate(counts))
[435] Fix | Delete
if len(cum_counts) != n:
[436] Fix | Delete
raise ValueError('The number of counts does not match the population')
[437] Fix | Delete
total = cum_counts.pop()
[438] Fix | Delete
if not isinstance(total, int):
[439] Fix | Delete
raise TypeError('Counts must be integers')
[440] Fix | Delete
if total <= 0:
[441] Fix | Delete
raise ValueError('Total of counts must be greater than zero')
[442] Fix | Delete
selections = self.sample(range(total), k=k)
[443] Fix | Delete
bisect = _bisect
[444] Fix | Delete
return [population[bisect(cum_counts, s)] for s in selections]
[445] Fix | Delete
randbelow = self._randbelow
[446] Fix | Delete
if not 0 <= k <= n:
[447] Fix | Delete
raise ValueError("Sample larger than population or is negative")
[448] Fix | Delete
result = [None] * k
[449] Fix | Delete
setsize = 21 # size of a small set minus size of an empty list
[450] Fix | Delete
if k > 5:
[451] Fix | Delete
setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
[452] Fix | Delete
if n <= setsize:
[453] Fix | Delete
# An n-length list is smaller than a k-length set.
[454] Fix | Delete
# Invariant: non-selected at pool[0 : n-i]
[455] Fix | Delete
pool = list(population)
[456] Fix | Delete
for i in range(k):
[457] Fix | Delete
j = randbelow(n - i)
[458] Fix | Delete
result[i] = pool[j]
[459] Fix | Delete
pool[j] = pool[n - i - 1] # move non-selected item into vacancy
[460] Fix | Delete
else:
[461] Fix | Delete
selected = set()
[462] Fix | Delete
selected_add = selected.add
[463] Fix | Delete
for i in range(k):
[464] Fix | Delete
j = randbelow(n)
[465] Fix | Delete
while j in selected:
[466] Fix | Delete
j = randbelow(n)
[467] Fix | Delete
selected_add(j)
[468] Fix | Delete
result[i] = population[j]
[469] Fix | Delete
return result
[470] Fix | Delete
[471] Fix | Delete
def choices(self, population, weights=None, *, cum_weights=None, k=1):
[472] Fix | Delete
"""Return a k sized list of population elements chosen with replacement.
[473] Fix | Delete
[474] Fix | Delete
If the relative weights or cumulative weights are not specified,
[475] Fix | Delete
the selections are made with equal probability.
[476] Fix | Delete
[477] Fix | Delete
"""
[478] Fix | Delete
random = self.random
[479] Fix | Delete
n = len(population)
[480] Fix | Delete
if cum_weights is None:
[481] Fix | Delete
if weights is None:
[482] Fix | Delete
floor = _floor
[483] Fix | Delete
n += 0.0 # convert to float for a small speed improvement
[484] Fix | Delete
return [population[floor(random() * n)] for i in _repeat(None, k)]
[485] Fix | Delete
try:
[486] Fix | Delete
cum_weights = list(_accumulate(weights))
[487] Fix | Delete
except TypeError:
[488] Fix | Delete
if not isinstance(weights, int):
[489] Fix | Delete
raise
[490] Fix | Delete
k = weights
[491] Fix | Delete
raise TypeError(
[492] Fix | Delete
f'The number of choices must be a keyword argument: {k=}'
[493] Fix | Delete
) from None
[494] Fix | Delete
elif weights is not None:
[495] Fix | Delete
raise TypeError('Cannot specify both weights and cumulative weights')
[496] Fix | Delete
if len(cum_weights) != n:
[497] Fix | Delete
raise ValueError('The number of weights does not match the population')
[498] Fix | Delete
total = cum_weights[-1] + 0.0 # convert to float
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function