Reputation: 31
I have been asked to simulate rolling two fair dice with sides 1-6. So the possible outcomes are 2-12.
my code is as follows:
def dice(n):
x=random.randint(1,6)
y=random.randint(1,6)
for i in range(n):
z=x+y
return z
My problem is that this is only returning the outcome of rolling the dice 1 time, so the outcome is always 2-12. I want it to return the sum of rolling the dice (n) times.
Does anyone have any suggestions for me?
Upvotes: 3
Views: 47638
Reputation: 11
With
import random
def roll_dice(times: int):
times_runned = 0
while times_runned < times:
result = random.randint(1, 6) + random.randint(1, 6)
print(result)
times_runned += 1
roll_dice(6)
you get something like
8
6
8
9
9
11
in the console output.
Upvotes: 1
Reputation: 1121346
Roll the dice in the loop:
import random
def dice(n):
total = 0
for i in range(n):
total += random.randint(1, 6)
return total
The +=
augmented assignment operator basically comes down to the same thing as total = total + random.randint(1, 6)
when summing integers (it is slightly more complicated than that, but that only matters for mutable objects like lists).
You could even use a generator expression and the sum()
function:
def dice(n):
return sum(random.randint(1, 6) for _ in range(n))
This basically does the same thing as the for
loop in the first example; loop n
times, summing up that many random numbers between 1 and 6 inclusive.
If instead of rolling n
times, you need to produce n
results of 2 dice rolls, you still need to roll in the loop, and you need to add the results to a list:
def dice(n):
rolls = []
for i in range(n):
two_dice = random.randint(1, 6) + random.randint(1, 6)
rolls.append(two_dice)
return rolls
This too can be written out more compactly, with a list comprehension:
def dice(n):
return [random.randint(1, 6) + random.randint(1, 6) for _ in range(n)]
You could also use random.choice()
from a list of generated sums; these are automatically weighted correctly; this basically pre-computes the 36 possible dice values (11 unique), each with equal probability:
from itertools import product
two_dice_sums = [a + b for a, b in product(range(1, 7), repeat=2)]
def dice(n):
return [random.choice(two_dice_sums) for _ in range(n)]
Either way, you'll get a list with n
results:
>>> dice(5)
[10, 11, 6, 11, 4]
>>> dice(10)
[3, 7, 10, 3, 6, 6, 6, 11, 9, 3]
You could pass the list to the print()
function to have these printed on one line, or on separate lines:
>>> print(*dice(5))
3 7 8 6 4
>>> print(*dice(5), sep='\n')
7
8
7
8
6
Upvotes: 7