Dice probability problem
Alexander Schmolck
a.schmolck at gmail.com
Wed Apr 5 08:55:58 EDT 2006
Tomi Lindberg <tomi.lindberg.NO_SPAM at pp.inet.fi.invalid> writes:
> # Adds another die to results.
> def add_dice(sums, die):
> # If first die, all values appear once
I'd add something like
sums = sums or {}
because otherwise your function will sometimes mutate sums and sometimes
return a fresh object, which usually is a very bad thing as it can easily lead
to quite nasty bugs.
> 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
'as
More information about the Python-list
mailing list