我想生成一个随机分布的数字列表,以便它们的总和等于随机选择的数字。例如,如果随机选择的数字是 5,则分布将是 [1 2 2] 或 [2 3] 或 [1 1 1 2] 等。 欢迎任何建议!
最佳答案
让 n
成为您希望值相加的数字。生成随机大小(小于 n
)的随机 sample
,由 1 到 n
范围内的值组成,n
。现在添加端点 0 和 n
,然后排序。排序值的连续差异总和为 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]
如果您希望能够明确指定总和中的项数,或者在未指定的情况下使其随机,请添加一个可选参数:
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
关于python - 如何生成随机数列表,使它们的总和等于随机选择的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31811267/