如何生成随机数列表,以便它们的总和等于随机选择的数 [英] How to generate a list of random numbers so their sum would be equal to a randomly chosen number
问题描述
我想生成一个数字随机分布的列表,以便它们的总和等于一个随机选择的数字.例如,如果随机选择的数字为5,则分布将为[1 2 2]或[2 3]或[1 1 1 2],依此类推. 欢迎任何建议!
I want to generate a list of random distribution of numbers so their sum would be equal to a randomly chosen number. For example, if randomly chosen number is 5, the distribution would be [1 2 2] or [2 3] or [1 1 1 2] and so on. Any suggestions are welcome!
推荐答案
让n
为您希望将值相加的数字.生成具有随机大小(小于n
)的随机sample
,该随机sample
由1到n
范围内的值组成,不包括n
.现在添加端点0和n
,并进行排序.排序后的值的连续差异总和为n
.
Let n
be the number you want values to add up to. Generate a random sample
of random size (less than n
), consisting of values in the range 1 to n
exclusive of n
. Now add the endpoints 0 and n
, and sort. Successive differences of the sorted values will sum to n
.
import random as r
def random_sum_to(n):
a = r.sample(range(1, n), r.randint(1, n-1)) + [0, n]
list.sort(a)
return [a[i+1] - a[i] for i in range(len(a) - 1)]
print(random_sum_to(20)) # yields, e.g., [4, 1, 1, 2, 4, 2, 2, 4]
如果您希望能够明确指定总和中的项数,或者如果未指定则为随机数,请添加可选参数:
If you'd like to be able to specify the number of terms in the sum explicitly, or have it be random if unspecified, add an optional argument:
import random as r
def random_sum_to(n, num_terms = None):
num_terms = (num_terms or r.randint(2, n)) - 1
a = r.sample(range(1, n), num_terms) + [0, n]
list.sort(a)
return [a[i+1] - a[i] for i in range(len(a) - 1)]
print(random_sum_to(20, 3)) # [9, 7, 4] for example
print(random_sum_to(5)) # [1, 1, 2, 1] for example
这篇关于如何生成随机数列表,以便它们的总和等于随机选择的数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!