Skip to content Skip to sidebar Skip to footer

Getting Values Of Each Number To Be Not More 90

I have a code which generates random number and put them in a list. The total of the values of these number must follow a defined value (in this case 6066). The numbers in the list

Solution 1:

One solution will be to consider the problem like you are trying to distribute 6066 items between 95 buckets and each one has a capacity of 85, so you just loop over the items and each time choose a bucket that is not already full.

Here is a simple implementation. It won't be particularly fast, but it avoids the need to backtrack because there is no possibility of violating the rules (total sum incorrect or individual value exceeds the maximum).

Note that other solutions that are equally valid within your rules may have a different probability distribution, but you have not said anything about what probability distribution you require.

import random

def num(n, total, maxv):

    if total > n * maxv:
        raise ValueError("incompatible requirements")

    vals = [0 for _ in range(n)]
    not_full = list(range(n))

    for _ in range(total):
        index = random.choice(not_full)
        vals[index] += 1
        if vals[index] == maxv:
            not_full.remove(index)

    return vals

answer = num(95, 6066, 85)

print(answer)
print(max(answer))
print(sum(answer))

Gives:

[59, 59, 73, 63, 77, 58, 54, 71, 73, 67, 69, 67, 58, 79, 63, 59, 80, 58, 77, 64, 62, 64, 54, 50, 64, 72, 62, 69, 81, 61, 63, 50, 65, 56, 60, 51, 59, 61, 63, 56, 67, 69, 69, 64, 85, 66, 74, 66, 63, 63, 63, 68, 84, 66, 53, 82, 59, 66, 63, 58, 67, 58, 59, 58, 69, 56, 63, 61, 73, 58, 65, 60, 61, 53, 68, 51, 58, 57, 67, 60, 65, 73, 63, 59, 62, 49, 66, 59, 64, 56, 69, 58, 61, 67, 74]
856066

Post a Comment for "Getting Values Of Each Number To Be Not More 90"