-1

I've asked the question a couple of times but I'm trying to reproduce a solution in Python from the book "Bayesian Statistics The Fun Way".

The question is: What is the probability of rolling three six-sided dices and getting a value of greater than 7?

The answer in the book says there are 218 possible outcomes, of which 181 are outcomes are greater than 7.

The code in R, which I've tried to reproduce in Python is:

count <- 0
for (roll1 in c(1:6){
   for(roll2 in c(1:6){
       for(roll3 in c(1:6){
            count <-count + ifelse(roll1+roll2+roll3 > 7,1,0)
    }
  }
}

Tried this code where thankfully the community helped on getting an output from a function: https://stackoverflow.com/questions/72909169/confused-about-output-from-python-function

Then wanted to create a list of tuples to create set

But suspect I'm tying myself in circles, and am seeking a pointer rather than a solution. The results should be 216 permutations and 181 where result of sum is 181.

halfer
  • 19,824
  • 17
  • 99
  • 186
elksie5000
  • 7,084
  • 12
  • 57
  • 87

1 Answers1

3

Equivalent Python Code:

count = 0
for roll1 in range(1, 7): # Equivalent to R for (roll1 in c(1:6){
    for roll2 in range(1, 7):
        for roll3 in range(1, 7):
            # Use Python conditional expression in place of R ifelse
            count += 1 if roll1 + roll2 + roll3 > 7 else 0

print(count) # Output: 181

Alternatively:

sum(1 
    for roll1 in range(1, 7) 
    for roll2 in range(1, 7) 
    for roll3 in range(1, 7)
    if roll1 + roll2 + roll3 > 7)

2nd Alternative (from aneroid comment):

sum(roll1 + roll2 + roll3 > 7
    for roll1 in range(1, 7) 
    for roll2 in range(1, 7) 
    for roll3 in range(1, 7))
DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • And 2nd Alternatively: `sum(roll1 + roll2 + roll3 > 7 ...` :-) Since `True` evaluates to `1` and `False` to `0`. – aneroid Jul 10 '22 at 14:58
  • @aneroid -- yes, that's also very good since it takes advantage of the value of booleans in arithmetic. – DarrylG Jul 10 '22 at 15:00