Skip to content

Instantly share code, notes, and snippets.

@fyxme
Created September 7, 2017 06:58
Show Gist options
  • Save fyxme/bfda497a7bc1248205f6b91712a3b6d0 to your computer and use it in GitHub Desktop.
Save fyxme/bfda497a7bc1248205f6b91712a3b6d0 to your computer and use it in GitHub Desktop.
from random import random
from time import time
from multiprocessing import Pool
import matplotlib.pyplot as plt
def _avg(results):
return sum(results) / float(len(results))
def _range(results):
return (min(results), max(results))
def _median(results):
n = len(results)
if not n % 2:
return sum(sorted(results)[n//2-1:n//2+1])/float(2)
return sorted(results)[n//2]
def test(_,cards=52):
pulls = 0
found = 0
odds_to_discover = 1 - found / float(cards)
while odds_to_discover:
if odds_to_discover >= random():
found += 1
odds_to_discover = 1 - found / float(cards)
pulls += 1
return pulls
def threaded_tests(num_threads=4, num_tests=1000):
results = list()
pool = Pool(num_threads)
results = pool.map(
test,
xrange(num_tests))
pool.close();
pool.join();
return results
def main():
num_tests = 10000000
num_threads = 12
start = time()
results = threaded_tests(num_threads=num_threads,num_tests=num_tests)
end = time() - start
avg = _avg(results)
median = _median(results)
rnge = _range(results)
print "Num. of trials: %s" % num_tests
print "Avg. : %s" % avg
print "Median : %s" % median
print "Range : [%s - %s]" % rnge
print "Time (in sec): %s" % end
plt.hist(results,bins=(rnge[1]-rnge[0]))
plt.xlabel("Days to collect 52 cards")
plt.ylabel("Number of tests")
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment