Python Forum
Some exercises I need help with.
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some exercises I need help with.
#1
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!
Reply
#2
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.
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Mission Impossible : New to Python and 3 days to do theses exercises Kangaaxx 6 3,704 Aug-16-2018, 05:58 PM
Last Post: Kangaaxx
  3 Finance Python Exercises mmkthen 2 5,388 Oct-29-2017, 02:55 PM
Last Post: sparkz_alot
  One of my exercises is breaking my balls. Jei 14 13,681 Dec-03-2016, 03:35 PM
Last Post: Jei

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020