Rolling Dice
Credit: Tim Keating
Problem
You need to generate pseudo-random numbers simulating the roll of several dice, in which the number of dice and number of sides on each die are parameters.
Solution
An implicit loop performed by the reduce built-in
function turns out to be the fastest solution, although this is not
immediately obvious:
import random
def dice(num, sides):
return reduce(lambda x, y, s=sides: x + random.randrange(s),
range(num+1)) + numIf you prefer to avoid lambda in favor of a named
nested function, here is an equivalent but somewhat more readable
alternative:
def dice(num, sides):
def accumulate(x, y, s=sides): return x + random.randrange(s)
return reduce(accumulate, range(num+1)) + numDiscussion
This recipe presents a simple but subtle
function that permits you to generate random numbers by emulating a
dice roll. The number of dice and the number of sides on each die are
the parameters of the function. For example, to roll four six-sided
dice, you would call dice(4, 6). Simulating a dice
roll is a good way to generate a random number with an expected
binomial profile. For example, rolling three six-sided dice will
generate a bell-shaped (but discrete) probability curve with an
average of 10.5.
After trying a more manual approach (a for loop
with an accumulator), I found that using
reduce is generally faster.
It’s possible that this implementation could be
faster still, as I haven’t profiled it very
aggressively. But it’s fast enough for my purposes.
This recipe’s ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access