number generator

shellux liyehua1986 at gmail.com
Sat Mar 10 23:12:57 EST 2007


On Mar 9, 10:44 pm, "cesco" <fd.calabr... at gmail.com> wrote:
> 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


import random

def genRandList(n,left):
   L = []
   if n > left:
      return L

   while n:
      L.append(int(random.random()*(left-n+1))+1)
      n -= 1;
      left -= L[-1]

   return L




More information about the Python-list mailing list