Dice probability problem
Tomi Lindberg
tomi.lindberg.NO_SPAM at pp.inet.fi.invalid
Tue Apr 4 12:10:03 EDT 2006
First, thanks to Antoon and Alexander for replying.
Antoon Pardon wrote:
> It would be better to construct distributions for one
> die and make a function that can 'add' two distributions
> together.
As both replies pointed to this direction, I tried to take
that route. Here's the unpolished code I came up with. Does
it look even remotely sane way to accomplish my goal?
-- code begins --
# A die with n faces
D = lambda n: [x+1 for x in range(n)]
# A new die with 6 faces
d6 = D(6)
# Adds another die to results.
def add_dice(sums, die):
# If first die, all values appear once
if not sums:
for face in die:
sums[face] = 1
# Calculating the number of appearances for additional
# dice
else:
new_sums = {}
for k in sums.keys():
for f in die:
if new_sums.has_key(k+f):
new_sums[k+f] += sums[k]
else:
new_sums[k+f] = sums[k]
sums = new_sums
return sums
sums = add_dice({}, d6)
sums = add_dice(sums, d6)
sums = add_dice(sums, d6)
-- code ends --
Thanks,
Tomi Lindberg
More information about the Python-list
mailing list