Reputation: 11
I am really confused with what I'm doing here I am not sure why it is not working for me. I can print out random rolls for numbers 1-6 but now I am trying to do two other things:
import random
def rollDie(number):
rolls = [0] * 6
for i in range(0, number):
roll=int(random.randint(1,6))
rolls[roll - 1] += 1
return rolls
if __name__ == "__main__":
result = rollDie(50)
i = result
print (result)
print(i/6)
Upvotes: 0
Views: 2313
Reputation: 37
Try this:
import random
def rollDie(number): # cleaner version
results = []
for i in range(0, number):
results.append(random.randint(1, 6))
return results
def most_common(lst): # quick dirty lambda to calc the most occurring roll
return max(((item, lst.count(item)) for item in set(lst)), key=lambda a: a[1])[0]
results = rollDie(50) # 50 rolls
total = 0 # creating total
for i in results:
total += i # adding up all the dice rolls
print(total) # total
print(total / 50) # Average from the 50 dice rolled
print(round(total / 50)) # rounded Average
print(most_common(results)) # most occuring number
Upvotes: 0
Reputation: 44
The first question you pose needs a bit of clarification; what is it exactly that you are looking for in the "average" value thrown? To answer your second question, the function you gave us conducts a number amount of dice rolls, saving them to a list corresponding to each die number. All you have to do to see the most popular face rolled is print the list and look for the largest number. Alternatively, you can use the array.index( max( array ) )
to find the index or 'die face' of the most rolled face.
import random
def rollDie(number):
rolls = [0] * 6
for i in range(0, number):
roll=int(random.randint(1,6)) # try to avoid naming things like this
rolls[roll - 1] += 1
return rolls
if __name__ == "__main__":
result = rollDie(50)
i = result
print (result) # you can just look at the largest value in the array
print(i/6) # this is dividing a list by an integer....
print result.index(max(result)) # This will print the index of the post rolled face
# i.e if one was the most rolled it would print 0
To be more explicit what you should have is:
import random
def rollDie(number):
rolls = [0] * 6
for i in range(0, number):
roll=int(random.randint(1,6))
rolls[roll - 1] += 1
return rolls
result = rollDie(50)
print (result)
print result.index(max(result))
Upvotes: 1