Created
May 10, 2014 15:03
-
-
Save foxx/b36138811f61305ffc66 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import random | |
from pprint import pprint as p | |
CHOICES = ['G', 'G', 'G', 'G', 'B', 'B'] | |
ANSWERS = [ | |
'BGBBB', | |
'GBGBBB', | |
'GBBBBB' | |
] | |
ATTEMPTS = 2000 | |
def run(): | |
print """ | |
#################################################### | |
# | |
# Reproducing 'dice roll' from the video | |
# [27C3] (en) Cognitive Psychology for Hackers | |
# See http://www.youtube.com/watch?v=uJAuAuGboOM (14:00m) | |
# | |
# cal.leeming [at] simplicitymedialtd.co.uk | |
# 03/02/2013 | |
# | |
#################################################### | |
- Choices: %s | |
- Answers: %s | |
- Attempts: %s | |
Place your bets.. | |
""" % ( | |
CHOICES, ANSWERS, ATTEMPTS | |
) | |
# find the maximum string length of our answers | |
maxlen = max(ANSWERS, key=lambda x: len(x)) | |
# sort our answers by shortest first | |
ans = sorted(ANSWERS, key=lambda x: len(x)) | |
# temp assign | |
results = [] | |
count = 0 | |
while True: | |
# check if we are finished | |
if len(results) >= ATTEMPTS: | |
break | |
# increment counters | |
count += 1 | |
# generate a random string based on the maximum length | |
# of our answers | |
r = map(lambda x: random.choice(CHOICES), maxlen) | |
r = "".join(r) | |
# attempt to match one of our answers, starting with shortest first | |
for x in ans: | |
# trim the result down to the same size as the answer | |
if r[:len(x)] == x: | |
o = (x, count) | |
results.append(o) | |
count = 0 | |
# calculate total iterations | |
total_iter = sum(map(lambda x: x[1], results)) | |
# calculate total found for each answer | |
final = [] | |
for x in ans: | |
r = filter(lambda s: s[0] == x, results) | |
found = len(r) | |
hits = sum(map(lambda s: s[1], r)) | |
o = ( x, hits, found, ) | |
final.append(o) | |
# find our winner | |
winner = sorted(final, key=lambda x: x[2])[-1][0] | |
print "Our winner is: %s" % ( winner, ) | |
# header sprintf | |
h = "%-10s %-10s %-15s %-15s" | |
print h % ( "Answer", "Found", "Total chance", "Compared chance" ) | |
# print stats | |
for x in final: | |
answer = x[0] | |
hits = x[1] | |
found = x[2] | |
# calculate percentage against total iters | |
perc1 = (float(found) / float(total_iter) ) * 100 | |
perc1 = "%.3f%%" % ( perc1, ) | |
# calculate percentage against total attempts | |
perc2 = (float(found) / float(ATTEMPTS) ) * 100 | |
perc2 = "%.3f%%" % ( perc2, ) | |
print h % ( answer, found, perc1, perc2, ) | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment