I am trying to write an algorithm that would pick N distinct items from an sequence at random, without knowing the size of the sequence in advance, and where it is expensive to iterate over the sequence more than once. For example, the elements of the sequence might be the lines of a huge file.
I have found a solution when N=1 (that is, "pick exactly one element at random from a huge sequence"):
import random
items = range(1, 10) # Imagine this is a huge sequence of unknown length
count = 1
selected = None
for item in items:
if random.random() * count < 1:
selected = item
count += 1
But how can I achieve the same thing for other values of N (say, N=3)?
random.sample(your_collection, N)
.range(1, 10)
. Is this really an XY question for asking "How to determine/estimate upper-bound of iterator length (without iterating)?". For example, if it was a text file, we simply get(/estimate) the file size, then divide by an estimated average/max/min line length (in characters). (and for Unicode, estimate character length in bytes)__length_hint__()
Can I speedup an iterable class when I know it's length in advance?. And also, it's generally not necessary to call your entire file into memory to estimate its line-length/record-length/whatever. So, what type of data are you handling, and how do we efficiently estimate (upper-bound) for its length?