最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何生成随机数列表,以便它们的总和等于随机选择的数

SEO心得admin45浏览0评论
本文介绍了如何生成随机数列表,以便它们的总和等于随机选择的数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

评论列表(0)

  1. 暂无评论