Skip to content

Instantly share code, notes, and snippets.

@jeremyvisser
Created May 30, 2015 07:26
Show Gist options
  • Save jeremyvisser/e814cf0327dafb4f091e to your computer and use it in GitHub Desktop.
Save jeremyvisser/e814cf0327dafb4f091e to your computer and use it in GitHub Desktop.
Alex Bellos' method of winning a guessing game
#!/usr/bin/env python3
""" Test Alex Bellos' method of winning a guessing game.
Take two random numbers, a and b. The objective is to
guess whether a is greater than or less than b.
You might think you have a 50% chance of guessing correctly,
which is true if guessed randomly.
However, Alex Bellos on Numberphile suggests a different method:
Pick a third random number, k, and instead pretend k is b.
Compare a against k and use this to decide how a compares to b.
This is unintuitive, so the best way to check is to simulate.
Reference: https://www.youtube.com/watch?v=ud_frfkt1t0
"""
import sys
import random
random.seed()
def random_guess(a, k):
""" Return '<' or '>' randomly.
Should be 50% probability of being right.
Does not look at k.
"""
return random.choice(('<', '>'))
def bellos_guess(a, k):
""" Return Alex Bellos' educated guess.
Generate random number and guess against that instead.
Allegedly >50% probability of being right.
"""
if a < k:
return '<'
if a > k:
return '>'
raise ValueError
def simulation(guess_method, samples):
correctness = 0
for i in range(samples):
# get three unique integers from range 1-99
a, b, k = random.sample( range(1,100), 3 )
# don't tell the method what b is
guess = guess_method(a, k)
correct = (a < b) == (guess == '<')
if correct:
correctness += 1
return correctness / samples * 100
if __name__ == '__main__':
try:
samples = int(sys.argv[1])
except (IndexError, ValueError):
samples = 1000000 # default to one million samples
print("Running simulation with %d samples" % samples)
print(
"\tRandom guess = %f%% correctness"
% simulation(random_guess, samples=samples)
)
print(
"\tBellos guess = %f%% correctness"
% simulation(bellos_guess, samples=samples)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment