Python: 生成 5 个具有固定和的随机整数(每个都有自己的范围)

Python: generate 5 random int (every has own range) with fixed sum

import random
#lets take kg(for Total) for better understanding

Total = random.randint(40, 110) #For example Total=100   kg and this is 100%

Total = (a+b+c+d+e) 
 

Total 中的每个值都有自己的范围(以 % 为单位)。

首先:找到随机值(在总计 % 的范围内)。

我试过了(但是 sum() 可以 >or< 小于 100):

a=random.randint(40, 70)

b=random.randint(0, 4)

c=random.randint(0, 2)

d=random.randint(22, 44)

e=random.randint(0, 7)

其次:求出a,b,c,d,e的精确值(根据第一部分总计的百分比)。我试过这个:

a=Total*random.randint(40, 70)/100

b=Total*random.randint(0, 4)/100

c=Total*random.randint(0, 2)/100

d=Total*random.randint(22, 44)/100

e=Total*random.randint(0, 7)/100

此代码无效。请帮忙

试试这个:

import random

random_ints = []
sum_randoms = 0
upper_limit = 100
while sum(random_ints) < 100 and len(random_ints) < 5:
    random_int = random.randint(0, upper_limit)
    random_ints.append(random_int)
    upper_limit = 100 - sum(random_ints)

random_ints.append(100 - sum(random_ints))

print(random_ints)

我会先从最小的范围开始,然后选择最后一个不是随机的,而是作为其他 4 和 100 之和的差值。由于不能保证随机数满足所有约束,您可能需要继续选择,直到得到满意的答案。

def sum_to_100(range_list):
    if sum(lo for lo,hi in range_list) > 100 or sum(hi for lo,hi in range_list) < 100:
        raise ValueError('Solution is impossible within the constraints')
    ordered_ranges = sorted((lo,hi,i) for i,(lo,hi) in enumerate(range_list))
    n = len(range_list)
    solution = []
    while len(solution) != n or sum(solution) != 100:
        index = len(solution)
        lo, hi, i = ordered_ranges[index]
        if index == n - 1:
            final = 100 - sum(solution)
            if lo <= final <= hi:
                solution.append(final)
            else:  # start over
                solution = []
        else:
            solution.append(random.randint(lo, hi))
    # restore the original order
    solution = [num for i,num in sorted(enumerate(solution), key=lambda x:ordered_ranges[x[0]][2])]
    return solution

>>> sum_to_100([(40, 70), (0, 4), (0, 2), (22, 44), (0, 7)])
[59, 3, 1, 32, 5]
>>> sum_to_100([(40, 70), (0, 4), (0, 2), (22, 44), (0, 7)])
[47, 2, 0, 44, 7]