Army1987 <[EMAIL PROTECTED]> wrote: > "cesco" <[EMAIL PROTECTED]> ha scritto nel messaggio > news:[EMAIL PROTECTED] > >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 -- http://mail.python.org/mailman/listinfo/python-list