[issue37682] random.sample should support iterators
Serhiy Storchaka
report at bugs.python.org
Thu Jul 25 13:50:06 EDT 2019
Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:
Possible implementation:
from itertools import islice as _islice
def reservoir_sample(self, population, k):
if k < 0:
raise ValueError("Sample is negative")
it = iter(population)
result = list(_islice(it, k))
if len(result) < k:
raise ValueError("Sample larger than population")
self.shuffle(result)
randbelow = self._randbelow
for i, x in enumerate(it, k+1):
j = randbelow(i)
if j < k:
result[j] = x
return result
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37682>
_______________________________________
More information about the Python-bugs-list
mailing list