Skip to content

Instantly share code, notes, and snippets.

@tcg
Created April 25, 2016 15:26
Show Gist options
  • Save tcg/2743955a30683afb6e20292f79e703c0 to your computer and use it in GitHub Desktop.
Save tcg/2743955a30683afb6e20292f79e703c0 to your computer and use it in GitHub Desktop.
Some Python code to tinker with the ideas presented in the Numberphile episode "How to Win a Guessing Game".
"""
Some Python code to tinker with the ideas presented
in the Numberphile episode "How to Win a Guessing Game".
See: https://www.youtube.com/watch?v=ud_frfkt1t0
"""
import random
import time
a = None
b = None
k = None
loss = 0
wins = 0
ties = 0
fmt_intro = " a | b | k "
fmt = """{a} | {b} | {k}"""
print fmt_intro
for i in range(1000): # Number of "tries".
a = random.randint(1, 100) # Pick an integer between 1 and 100, inclusive.
b = random.randint(1, 100)
k = 50 # In this trial, I am setting `k` to a constant value.
if a > k:
# Guess that `A` will be the larger number...
if a > b:
wins += 1
else:
loss += 1
elif a < k:
# Guess that `B` will be the larger number...
if a < b:
wins += 1
else:
loss += 1
elif a == k:
# Unclear how to count these, so we specifically
# keep track of ties.
ties += 1
print fmt.format(
a=str(a).rjust(5),
b=str(b).rjust(5),
k=str(k).rjust(5)
)
# Does sleeping mess with the PRNG? Try it.
# time.sleep(float("0.001"))
print "Wins:", wins
print "Loss:", loss
print "Ties:", ties
print "-" * 70
# Percentage of Wins, out of Tries. "i+1" because `i` is zero-based.
p1 = (float(wins) / float(i + 1)) * 100
print "Percent wins:", p1
print "-" * 70
@tcg
Copy link
Author

tcg commented Apr 25, 2016

Example output:

$ python guessing_game.py
    a |     b |     k
   81 |    68 |    50
   57 |    89 |    50
    7 |    36 |    50
    7 |    98 |    50
   28 |    58 |    50
   39 |    88 |    50
   83 |    68 |    50
   21 |    78 |    50
   81 |     3 |    50
   92 |    24 |    50
   98 |    57 |    50
[... snip! ...]
   59 |    71 |    50
    4 |    14 |    50
   64 |    53 |    50
    6 |    54 |    50
   90 |    21 |    50
   33 |    37 |    50
   15 |    30 |    50
   50 |    21 |    50
   24 |    24 |    50
   84 |    39 |    50
   28 |    88 |    50
   92 |    79 |    50
   81 |    93 |    50
   33 |    45 |    50
   53 |    65 |    50
   85 |    63 |    50
   97 |    42 |    50
    3 |    27 |    50
   59 |    34 |    50
   96 |    68 |    50
   45 |    21 |    50
Wins: 727
Loss: 261
Ties: 12
----------------------------------------------------------------------
Percent wins: 72.7
----------------------------------------------------------------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment