number generator

MonkeeSage MonkeeSage at gmail.com
Sat Mar 10 19:40:54 EST 2007


On Mar 10, 3:16 am, greg <g... at cosc.canterbury.ac.nz> wrote:
> Another possibility is to generate a list of N non-random
> numbers that sum to M, and then adjust them up or down
> by random amounts. By performing up/down adjustments in
> pairs, you can maintain the sum invariant at each step.
> So then it's just a matter of how long you want to go
> on fiddling with them.

Taking your comment and running with it...this is pretty much
cheating, and requires that M be evenly divisible by N, and only works
well with smaller N values, and selections are limited to numbers in
the 1 to (M/N)+(M/N) range...but hey; other than that it's perfect,
heh.

import random
N, M = 10, 80
D    = M/N
O    = [D] * N
C    = []
for i in O:
    C.append(random.randint(1, D-1))
for i in range(0, len(O), 2):
    O[i] -= C[i]
    if i == len(O)-1:
        O[random.randint(0, i-1)] += C[i]
    else:
        O[i+1] += C[i]
assert sum(O) == M
assert len(O) == N

Regards,
Jordan




More information about the Python-list mailing list