Created
April 25, 2016 15:26
-
-
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".
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
""" | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: