Created
December 27, 2012 16:04
-
-
Save mlbright/4389354 to your computer and use it in GitHub Desktop.
Calculate the expected percentage of pairs of socks recovered after randomly washing a sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculate the expected percentage of pairs of socks recovered | |
# after randomly washing a sample | |
from random import shuffle, sample | |
from collections import defaultdict | |
from time import clock | |
PAIRS = 20.0 | |
EXPERIMENTS = 1000000 | |
def pile(num_pairs): | |
p = [sock for sock in range(int(num_pairs))] | |
p.extend(p) | |
shuffle(p) | |
return p | |
socks = pile(PAIRS) | |
def num_washed_pairs(num_pairs,sample_size,debug=False): | |
wash = sample(socks,sample_size) | |
sock_counter = defaultdict(int) | |
for sock in wash: | |
sock_counter[sock] += 1 | |
result = float(sum([ v // 2 for v in sock_counter.values() ])) | |
if debug: | |
print socks | |
print wash | |
print sock_counter | |
print result | |
return result | |
def run(num_experiments,num_pairs,sample_size): | |
results = [] | |
for i in range(int(num_experiments)): | |
results.append(num_washed_pairs(num_pairs,int(sample_size))/num_pairs) | |
print "expected %% of sock pairs: %.5f" % (sum(results) / len(results)) | |
if __name__ == "__main__": | |
#num_washed_pairs(PAIRS,PAIRS,debug=True) | |
start = clock() | |
run(EXPERIMENTS,PAIRS,0.75*2*PAIRS) | |
print "time elapsed: %.4f" % (clock() - start) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment