Is there a built-in method to do it? If not how can I do this without costing too much overhead?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not built-in, but algorithm
R(3.4.2)(Waterman’s "Reservoir Algorithm") from Knuth’s "The Art of Computer Programming" is good (in a very simplified version):The
num, ... in enumerate(..., 2)iterator produces the sequence 2, 3, 4… Therandrangewill therefore be 0 with a probability of1.0/num— and that’s the probability with which we must replace the currently selected line (the special-case of sample size 1 of the referenced algorithm — see Knuth’s book for proof of correctness == and of course we’re also in the case of a small-enough "reservoir" to fit in memory ;-))… and exactly the probability with which we do so.