number generator
Raymond Hettinger
python at rcn.com
Wed Mar 14 05:39:22 EDT 2007
[Alex Martelli]
> map([random.randrange(5) for i in xrange(45)].count, xrange(5))
>
> i.e., this gives 5 integers (each between 0 and 45 included) summing to
> 45 -- add 1 to each of them to get the desired result.
This is a really nice approach. Besides being fast, it is not too
hard to see that it is correct.
FWIW, here's a variant with a count using the new defaultdict:
n, m = 5, 45
bag = collections.defaultdict(int)
for i in xrange(m):
bag[random.randrange(n)] += 1
ans = [bag[k] for k in range(n)]
More information about the Python-list
mailing list