I am trying to create a system that will roll different multi-sided dice in different quantities to determine the effect adding more dice has to the chances of getting the highest number.
import random
from statistics import mean
#define the dice
class Dice:
"""these are the dice to roll"""
def __init__(d, qty, sides):
d.qty = qty
d.sides = sides
q1d4 = Dice(1, 4)
q2d4 = Dice(2, 4)
q3d4 = Dice(3, 4)
q4d4 = Dice(4, 4)
#...removed extras for clarity
q5d20 = Dice(5, 20)
q6d20 = Dice(6, 20)
def Roll(Dice):
i = 0
while i < 10:
single_rolls = []
highest_of_rolls = []
avg_of_highest = []
qty = Dice.qty
sides = Dice.sides
At this line I am able to successfully roll a random number between 1 and the number of sides, and it appends to the list single_rolls and this is shown in the print statement:
for q in range(qty):
#rolls a single dice "qty" times and appends the result to single_rolls
single_rolls.append(random.randint(1, sides))
print(single_rolls)
I then am trying to append just the highest number from the single_rolls list to the highest_of_rolls list within the while loop for each iteration of rolls, and then averaging it:
highest_of_rolls.append(max(single_rolls))
print(highest_of_rolls)
i += 1
avg_of_highest = mean(highest_of_rolls)
print(avg_of_highest)
It doesn't seem to be appending to the highest_of_rolls list when I run it though. From the print statement it seems to be successfully finding the highest number from the two rolls, but the highest_of_rolls list does not seem to be growing like I would expect.
Finally at the end of the code the average is always just the last value that would have gone into highest_of_rolls and not anywhere near an average.
Here is an example of the output that seems suspicious:
>>> Roll(q2d20)
[11]
[11, 14]
[14]
[15]
[15, 1]
[15]
[4]
[4, 9]
[9]
[15]
[15, 2]
[15]
[1]
[1, 16]
[16]
[9]
[9, 3]
[9]
[18]
[18, 9]
[18]
[20]
[20, 11]
[20]
[13]
[13, 5]
[13]
[20]
[20, 10]
[20]
20
Even my simple understanding of statistics can see that 20 is not the average of multiple numbers below 20, and besides that number fluctuates wildly and is always simply the last number that would have gone into the highest_of_rolls list.
I feel like I have an indentation error somewhere, but I have tried multiple ways of writing this and it always seems to come out the same. Any help would be greatly appreciated.
He is not appending to highest_of_rolls
because in the beginning of your while
loop you reset the variable everytime. You should define highest_of_rolls
before the while statement, otherwise the variable will be cleared everytime you roll a dice.
Hope this is helpful.