Python Forum

Full Version: Some exercises I need help with.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I have an exercise where I have to calculate the probability from rolling a dice. I do have the probability from 1 side, but I need the probabality from all sides. So my problem is generalizing the code to make it work. This is what I have so far

import random

def prob_die(max_exp, outcome):
    counter = 0
    for _ in range(max_exp):
        s = random.randint(1,6) # roll
        if s==outcome:
            counter +=1
        return counter/max_exp

prob_die(100000, 6)
I was looking at one example which is this one

import random

random.seed()

ROLLED = {i: 0 for i in range(1, 7)}
ITERATIONS = int(input('How many times would you like to roll the dice? '))

def probability():
    print("Calculation of probability: ")
    for key, count in ROLLED.items():
        print("\t{}: {:.2f}".format(key, count*100./ITERATIONS*1.))

for _ in range(ITERATIONS):
    ROLLED[random.randint(1, 6)] += 1

probability()
But I can't seem to understand it quite well. Some help would be appreciated!
One thing:
in the following code:
def prob_die(max_exp, outcome):
    counter = 0
    for _ in range(max_exp):
        s = random.randint(1,6) # roll
        if s==outcome:
            counter +=1
        return counter/max_exp
The for loop is worthless as stands because you return unconditionally after the first iteration
did you mean for the return to be part of the if==outcome statement? if so indent.
The second code sets up a dictionary of the sides of the die and the counts: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}. So ROLLED[5] is the number of times a five has been rolled. The loop on line 13 rolls the die ITERATIONS times (however many times you want it to) and records the results of each roll. The probability function just prints the results.

You can do this with a list as well as a dictionary. ROLLED = [0] * 7 would work just as well, although you would have to rewrite the probability function.