number generator
Raymond Hettinger
python at rcn.com
Sat Mar 10 09:39:44 CET 2007
On Mar 9, 7:32 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> In <1173453432.893222.308... at j27g2000cwj.googlegroups.com>, cesco wrote:
> > Given two positive integers, N and M with N < M, I have to generate N
> > positive integers such that sum(N)=M. No more constraints.
>
> Break it into subproblems. Generate a random number X from a suitable
> range and you are left with one number, and the problem to generate (N-1)
> random numbers that add up to (M-X).
This approach skews the probabilities. The OP said for example with
N=5 and M=50 that a possible solution is [3, 11, 7, 22, 7]. You're
approach biases the probabilities toward solutions that have a large
entry in the first position.
To make the solutions equi-probable, a simple approach is to
recursively enumerate all possibilities and then choose one of them
with random.choice().
Raymond
More information about the Python-list
mailing list