aleax at mac.com
Wed Mar 14 15:12:54 CET 2007
Raymond Hettinger <python at rcn.com> wrote:
> [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)]
Neat -- and you can use 1+bag[k] in the LC to adjust the results if
needed, of course.
More information about the Python-list