number generator

Paulo da Silva psdasilvaX at esotericaX.ptX
Sat Mar 10 12:31:01 EST 2007


cesco escreveu:
> 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
> 

May be this is what you want ...
I didn't test it enough ... but seems fine.

from random import randint,shuffle

def GenRInt(m,n):
	"""Generate m positive ints whose sum is n"""
	# Generate a random list
	xl=[randint(1,n-m+1) for i in xrange(m)]
	s=sum(xl)
	if s==n: return xl
	# Adjust each value to make sum==n
	xl=[max(x*n/s,1) for x in xl]
	s=sum(xl)
	if s!=n:
		# Compensate for truncations
		if s>n:
			# s>n is supposed not to occur. Just in case ...
			ixs=filter(lambda x: xl[x]>1,range(m))
			shuffle(ixs)
			for i in ixs[:s-n]: xl[i]-=1
		else:
			ixs=range(m)
			shuffle(ixs)
			for i in ixs[:n-s]: xl[i]+=1
	return xl

# Test it ...

xl=GenRInt(10,50)
print xl,"->",sum(xl)

print

xl=GenRInt(100,10000)
print xl,"->",sum(xl)

print

xl=GenRInt(1000,1000)
print xl,"->",sum(xl)


Regards.
Paulo



More information about the Python-list mailing list