Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # Machine Learning!
- #
- # 1) Probability associate with a binary event (imbalanced coin flip)
- # 2) Ada bases her choice on previous outcomes
- #
- # Chances (depending on how random the computer is):
- # Heads: 0.6
- # Tails: 0.4
- #
- # Ratio is number_of_heads/number_of_tails and should give
- # the ratio between 0.6/0.4 after enough attempts
- import random
- class Computer: # AI class
- successes = 0
- heads = 0
- tails = 0
- # Bases choice on how many heads or tails are observed.
- # More heads, machine goes for heads, more tails, machine
- # goes for tails.
- def choose(self):
- if self.heads > self.tails:
- return True
- elif self.heads < self.tails:
- return False
- elif self.heads == self.tails:
- choice = random.randint(0, 1) # Randomly choose here
- if choice == 1:
- return True
- else:
- return False
- # Completely random, no weighting, used as control
- def randomchoose(self):
- choice = random.randint(0, 1)
- if choice == 1:
- return True
- else:
- return False
- # A combination, bases choice on number of heads/tails somewhat,
- # but not completely so probably more realistic
- def realchoose(self):
- if self.heads > self.tails: # More chance of choosing heads
- choice = random.randint(1, 10)
- if choice < 8:
- return True
- elif choice > 7:
- return False
- elif self.heads < self.tails: # More chance of choosing tails
- choice = random.randint(1, 10)
- if choice < 8:
- return False
- elif choice > 7:
- return True
- elif self.heads == self.tails:
- choice = random.randint(0, 1) # Randomly choose here
- if choice == 1:
- return True
- else:
- return False
- class Coin:
- rawflip = 0.0
- def flip(self):
- rawflip = random.randint(1, 10) # From 1 to exclude 0
- if rawflip < 7: #1, 2, 3, 4, 5, 6 (6/10 chance)
- return True
- elif rawflip > 6: #7, 8, 9, 10 (4/10 chance)
- return False
- def main():
- loop = 0
- ai = Computer()
- coin = Coin()
- loop = int(raw_input("How many times do you want ada to play?\n"))
- while True:
- print(str(loop) + ".\n")
- loop -= 1
- choice = ai.choose()
- result = coin.flip()
- if choice == True:
- print("Ada chooses heads")
- else:
- print("Ada chooses tails")
- if result == True:
- ai.heads += 1
- print("Coin was heads\n")
- else:
- ai.tails += 1
- print("Coin was tails\n")
- if choice == result:
- ai.successes += 1
- if loop == 0:
- break
- print("\nAda had " + str(ai.successes) + " successful guesses")
- print("\nAda counted:")
- print(str(ai.heads) + " heads")
- print(str(ai.tails) + " tails")
- h = float(ai.heads)
- t = float(ai.tails)
- print("\nAda estimates that:")
- print("Ratio: " + str(h/t))
- print("P(Heads) = " + str(h/(h+t)))
- print("P(Tails) = " + str(t/(h+t)))
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement