在python中生成一定范围内的N个正整数,加起来等于总和

2024-01-23

我看过其他帖子解决类似的问题。我知道如何生成 N 个正整数。我还知道如何限制随机生成的整数的总和。唯一的问题是满足 N 个值都不超出指定范围的条件。

e.g. generate_ints(n, total, low, high)应该生成 n 个值数组,使得每个值都在低值和高值之间,并且总和等于总数。任何指示/帮助将不胜感激。

e.g.generate_ints(4, 40, 4, 15)应该生成类似的东西

[7,10,13,10]

我不在乎数字是否重复,只要它们不是高度倾斜即可。我在用np.randon.randint(5,15,n)选择整数。

到目前为止,我已经尝试过以下方法,但它不起作用 -

import numpy as np 
import random 
from random import uniform as rand 

total=50 
n=10 
low=2 
high=15 
result=[] 
m=0 
nobs=1 
while nobs <= n: 
    if m >= (total - low): 
        last_num= total -new_tot 
        result.append(last_num) 
    else: 
        next_num=np.random.randint(low,high,1) 
        new_tot = sum(result) + next_num 
        result.append(next_num) 
        m=new_tot 
    nobs +=1 

print result 
print sum(result)

再次感谢。


import numpy as np

def sampler(samples, sum_to , range_list):
    assert range_list[0]<range_list[1], "Range should be a list, the first element of which is smaller than the second"
    arr = np.random.rand(samples)
    sum_arr = sum(arr)

    new_arr = np.array([int((item/sum_arr)*sum_to) if (int((item/sum_arr)*sum_to)>range_list[0]and int((item/sum_arr)*sum_to)<range_list[1]) \
                            else np.random.choice(range(range_list[0],range_list[1]+1)) for item in arr])
    difference = sum(new_arr) - sum_to
    while difference != 0:
        if difference < 0 :
                for idx in np.random.choice(range(len(new_arr)),abs(difference)):
                    if new_arr[idx] != range_list[1] :
                        new_arr[idx] +=  1

        if difference > 0:
                for idx in np.random.choice(range(len(new_arr)), abs(difference)):
                    if new_arr[idx] != 0 and new_arr[idx] != range_list[0] :
                        new_arr[idx] -= 1
        difference = sum(new_arr) - sum_to
    return new_arr

new_arr = sampler (2872,30000,[5,15])
print "Generated random array is :"
print new_arr
print "Length of array:", len(new_arr)
print "Max of array: ", max(new_arr)
print "min of array: ", min(new_arr)
print "and it sums up to %d" %sum(new_arr)

结果 :

Generated random array is :
[ 9 10  9 ...,  6 15 11]
Length of array: 2872
Max of array:  15
min of array:  5
and it sums up to 30000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在python中生成一定范围内的N个正整数,加起来等于总和 的相关文章

  • XGBoost 产生预测结果和概率

    我可能正在文档中查看它 但我想知道 XGBoost 是否有办法生成结果的预测和概率 就我而言 我正在尝试预测多类分类器 如果我能返回Medium 88 那就太好了 分类器 中 预测概率 88 参数 params max depth 3 ob
  • Python daysBetweenDate

    我想我可能有一个无限循环 因为每当我运行代码时 我都会收到一条错误消息 它说 程序因使用 13 CPU 秒而关闭 整个代码 应该以日期作为输入并输出第二天 此代码假设所有月份都是 30 天 除了daysBetweenDates功能正常 其他
  • PyPDF2 复制后返回空白 PDF

    def EncryptPDFFiles password directory pdfFiles success 0 Get all PDF files from a directory for folderName subFolders f
  • Boost Python:多态容器?

    我有一个方法 或函数 它返回对多态对象列表的引用 class A class B public A std list
  • python subprocess proc.stderr.read() 引入额外的行?

    我想运行一些命令并抓取输出到 stderr 的任何内容 我有两个版本的函数可以执行此操作 版本 1 def Getstatusoutput cmd Return status output of executing cmd in a she
  • 按共同日期对数组数据进行排序

    我有一个包含许多行和 3 列的 csv 文件 日期 代表和销售额 我想使用 Python 生成一个新数组 该数组按日期对数据进行分组 并且对于给定日期 按销售额对代表进行排序 例如 我的输入数据如下所示 salesData 201703 B
  • 如何在 Pandas 中将多列乘以一列

    我想拥有 df income 1 income 2 df mtaz proportion 返回这些列乘以df mtaz proportion 这样我就可以设置 df mtaz income 1 mtaz income 2 df income
  • 如何在欧洲使用 Cloud Dataflow 区域终端节点?

    是否可以将 Google Cloud Platform Dataflow 作业的区域更改为欧洲 我已将管道区域设置为europe west1 d但我无法更改工作本身的区域 我尝试更改管道选项中的区域 但这会导致错误 并且只有默认区域有效 p
  • 如何从 google place api for python 中的地点 id 获取地点详细信息

    我正在使用 Google Places API 和 Python 来构建一个食品集体智能应用程序 例如周围有哪些餐馆 他们的评级如何 营业时间是什么 等等 我正在Python中执行以下操作 from googleplaces import
  • 如何从包含许多表的 Excel 工作表中解析数据帧(使用 Python,可能使用 Pandas)

    我正在处理布局糟糕的 Excel 工作表 我正在尝试解析这些工作表并将其写入数据库 每个工作表可以有多个表 尽管这些可能的表格的标题是已知的 但哪些表格将位于任何给定的工作表上 它们在工作表上的确切位置也不是已知的 表格不以一致的方式对齐
  • 如何在Python中将字符串转换为包含一个元素的列表[重复]

    这个问题在这里已经有答案了 我有一个字符串 我想将其转换为其中只有一个元素的列表 a abc print list a output a b c Expected o p abc 正确的做法是什么 只需使用 a abc b a print
  • 如何在Python中比较枚举?

    从 Python 3 4 开始 Enum类存在 我正在编写一个程序 其中一些常量具有特定的顺序 我想知道哪种方式最适合比较它们 class Information Enum ValueOnly 0 FirstDerivative 1 Sec
  • 使用 South 更改 Django 模型列默认值

    我在 Django 项目中使用 South 和 Postgresql DB 我想更改一个模型字段的默认值以供继续使用 我不需要以前的记录 刚刚新记录 我是否需要为此进行迁移 或者只是更改模型 旧场详细信息 background style
  • Python,socket.error:[Errno 10049]

    在开发一个简单的聊天客户端的基础上 遇到以下错误 socket error Errno 10049 The requested address is not valid in its context 代码是 from socket impo
  • 哪些 2to3 修复程序输出有效的 Python 2 代码?

    2to3 是一个 Python 程序 它读取 Python 2 x 源代码并应用一系列修复程序将其转换为有效的 Python 3 x 代码 考虑一下列出的四十个修复者https docs python org 3 library 2to3
  • 在硬件级别模拟按键 - Windows

    我正在寻找一种语言或库 使我能够在最大可能的水平上模拟击键 而无需实际按下按键 我对击键级别的具体衡量标准是 当我的计算机已经运行按键侦听器 例如鼠标键和粘滞键 时 它是否会产生与物理按键相同的输出 我尝试过很多击键模拟的方法 java A
  • 在ActivePython-2.6中安装pyCurl?

    我过去曾使用过 pyCurl 并让它与我的系统默认 python 安装一起使用 但是 我有一个项目需要 python 更具可移植性 并且我正在使用 ActivePython 2 6 到目前为止 我安装任何其他模块都没有问题 但安装 pyCu
  • Python 和 Visual Studio Code - 如何在编辑器中运行特定文件?

    我正在使用 Visual Studio Code 和 Python 编写一个小型应用程序 我的应用程序有两个文件 Main py and MyCustomClass py Main py是应用程序的入口点 MyCustomClass py包
  • 从 Python 脚本创建可执行文件,同时获取较小的输出大小

    我的问题可能已经在某个地方得到了解答 但我仍然找不到直接的答案 我想从 python 代码创建一个独立的可执行文件 我已经尝试过很多解决方案 例如py2exe pyinstaller等等 但我的问题是输出文件大小很大 例如 在pyinsta
  • 通过 subprocess.communicate 在 python 脚本之间传输 pickled 对象输出

    我有两个 python 脚本 object generator py 它会腌制给定的对象并打印它 另一个脚本 object consumer py 通过 subprocess communicate 选择第一个脚本的输出 并尝试使用 pic

随机推荐