python - 如何生成随机数列表,使它们的总和等于随机选择的数字

标签 python list random distribution

我想生成一个随机分布的数字列表,以便它们的总和等于随机选择的数字。例如,如果随机选择的数字是 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/

相关文章:

python - scipy——如何从列表中随机提取数组

swift - 以随机顺序遍历文件

python - 在 Python 中使用多处理时如何共享自定义变量?

Python:将列表中的元素相互比较

python - 使用 Pandas,如何将行值拆分为单独的列,并使用它们的值?

Python:获取元组中每个字段名的 {(tuple): value } 字典的最大值

将目录树表示为递归列表

c++ - 用 vector C++ 中的随机数替换元素

python - featureFormat() 函数删除了一些点?

python - 在 python 中操作数据帧以进行 Glicko 计算