number generator

Alex Martelli aleax at mac.com
Sun Mar 11 15:12:50 EDT 2007


Army1987 <please.ask at for.it> wrote:

> "cesco" <fd.calabrese at gmail.com> ha scritto nel messaggio 
> news:1173451441.077648.321270 at c51g2000cwc.googlegroups.com...
> >I have to generate a list of N random numbers (integer) whose sum is
> > equal to M. If, for example, I have to generate 5 random numbers whose
> > sum is 50 a possible solution could be [3, 11, 7, 22, 7]. Is there a
> > simple pattern or function in Python to accomplish that?
> >
> > Thanks and regards
> > Francesco
> 
> 
> You can initialize a list to [1, 1, 1, 1, 1], and generate 45 random 
> integers between 1 and 5, and every time a number is generated, increase the
> Nth number in the list by one.
> 
> Not all distinct lists will have the same chance of occurring, e.g. [46, 1,
> 1, 1, 1] will be much less likely than [10, 10, 10, 10, 10]. Depending on
> what you need these numbers for, it can be a good thing or a bad thing.

And a1-liner way to get the numbers (net of the mandatory +1 for each)
is:

  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.

Without any specification regarding the distributions required for the
"5 random numbers" it's really impossible to say whether these are
better or worse than other proposed solutions.


Alex



More information about the Python-list mailing list