generated from mwc/lab_dice
Added methods to determine if there are at least n
of a kind in a roll of five dice. Similar to what was done in this lab, classes could be used to simulate coin tosses. I imagine then that simple board games could be simulated easily using classes, too.
This commit is contained in:
@@ -18,16 +18,54 @@ class FiveDice:
|
||||
if face != 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
def findn(self,nofakind):
|
||||
""" dice.findn(n) determines whether there are at least n of a kind in the roll and returns true if so and returns false otherwise. """
|
||||
nmuch = {} # create an empty dictionary to associate each face rolled with its frequency
|
||||
for die in dice.faces(): # go through each dice rolled
|
||||
if die in nmuch: # check if the dictionary already has the face included, and if so increase its frequency by 1
|
||||
nmuch[die] += 1
|
||||
if nmuch[die]==nofakind: # each time the dictionary is updated, check if the desired frequency has been achieved, and if so return true
|
||||
return True
|
||||
else:
|
||||
nmuch[die] = 1 # add the face to the dictionary with frequency 1 if it has not already been included
|
||||
return False # if the desired frequency was never achieved, return false
|
||||
|
||||
def is_three_of_a_kind(self):
|
||||
""" I didn't read the assignment carefully... this should return the result of dice.findn(3) """
|
||||
return dice.findn(3)
|
||||
|
||||
def is_four_of_a_kind(self):
|
||||
""" same issue... returns the result of dice.findn(4) """
|
||||
return dice.findn(4)
|
||||
|
||||
dice = FiveDice()
|
||||
successes = 0
|
||||
trials = 1000000
|
||||
|
||||
print("THIS IS THE ORIGINAL SIMULATION:")
|
||||
for trial in tqdm(range(trials)):
|
||||
dice.roll()
|
||||
if dice.all_ones():
|
||||
successes += 1
|
||||
|
||||
print(successes/trials)
|
||||
|
||||
|
||||
print("\n")
|
||||
print("THIS IS TO CHECK IF THERE ARE AT LEAST THREE OF A KIND:")
|
||||
successes = 0
|
||||
for trial in tqdm(range(trials)):
|
||||
dice.roll()
|
||||
# if dice.findn(3):
|
||||
if dice.is_three_of_a_kind():
|
||||
successes += 1
|
||||
print(successes/trials)
|
||||
|
||||
print("\n")
|
||||
print("THIS IS TO CHECK IF THERE ARE AT LEAST FOUR OF A KIND:")
|
||||
successes = 0
|
||||
for trial in tqdm(range(trials)):
|
||||
dice.roll()
|
||||
# if dice.findn(4):
|
||||
if dice.is_four_of_a_kind():
|
||||
successes += 1
|
||||
print(successes/trials)
|
||||
|
||||
Reference in New Issue
Block a user