Dice probability problem
Tomi Lindberg
tomi.lindberg.NO_SPAM at pp.inet.fi.invalid
Tue Apr 4 05:21:19 EDT 2006
Hi,
I'm trying to find a way to calculate a distribution of
outcomes with any combination of dice. I have the basics
done, but I'm a bit unsure how to continue. My main concern
is how to make this accept any number of dice, without
having to write a new list comprehension for each case?
Here's a piece of code that shows the way I'm doing things
at the moment.
-- code begins --
# A die with n faces
D = lambda n: [x+1 for x in range(n)]
# A pool of 3 dice with 6 faces each
pool = [D(6)] * 3
# A List of all outcomes with the current 3d6 pool.
results = [x+y+z for x in pool[0] for y in pool[1]
for z in pool[2]]
# A dictionary to hold the distribution
distribution = {}
# If outcome is already a key, adds 1 to its value.
# Otherwise adds outcome to keys and sets its value
# to 1.
def count(x):
if distribution.has_key(x): distribution[x] += 1
else: distribution[x] = 1
# Maps the results with above count function.
map(count, results)
-- code ends --
Thanks,
Tomi Lindberg
More information about the Python-list
mailing list