b = random.randint(2, 38)
a = random.randint(1, b - 1)
c = random.randint(b + 1, 39)
return [a, b - a, c - b, 40 - c]
(I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.)
Here's how it works:
- cut the total range in two randomly, that's b. The odd range is because there are going to be at least 2 below the midpoint and at least 2 above. (This comes from your 1 minimum on each value).
- cut each of those ranges in two randomly. Again, the bounds are to account for the 1 minimum.
- return the size of each slice. They'll add up to 40.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…