让n 成为您希望值相加的数字。生成随机大小的随机sample(小于n),由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