Skip to content

Instantly share code, notes, and snippets.

@Ceasar
Created August 11, 2012 18:41
Show Gist options
  • Save Ceasar/3326283 to your computer and use it in GitHub Desktop.
Save Ceasar/3326283 to your computer and use it in GitHub Desktop.
Small script to simulate an n-armed bandit game.
"""Module for playing the n-arm bandit game."""
import random
class Arm(object):
"""A point generator."""
def __init__(self):
self.mean = random.normalvariate(0, 1)
def pull(self):
"""Pull the lever and generate a random number."""
return random.normalvariate(self.mean, 1)
class Bandit(object):
"""Container for multiple arms."""
def __init__(self, n):
self.n = n
self.arms = [Arm() for _ in range(n)]
def pull(self, i):
"""Pull a specific arm."""
if i not in range(self.n):
raise IndexError("Not in range.")
else:
return self.arms[i].pull()
if __name__ == "__main__":
n = 10 # Number of decks
t = 20 # Number of turns
b = Bandit(n)
score = 0
print "Playing with %s decks." % n
print "Playing for %s turns." % t
turn = 0
while turn < t:
print "\nTurn %s. Your score is: %s" % (turn + 1, score)
i = raw_input("Please select a deck: ")
try:
result = b.pull(int(i))
print "You scored %s" % result
score += result
turn += 1
except ValueError:
print "Invalid number."
except IndexError:
print "Invalid deck."
print "Final score: %s" % score
for i, arm in enumerate(b.arms):
print "Arm %s mean: %s" % (i + 1, arm.mean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment