加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在一个范围内生成N个正整数,在python中累加总数

发布时间:2020-12-20 13:14:41 所属栏目:Python 来源:网络整理
导读:我看到其他帖子解决了类似的问题.我知道如何生成N个正整数.我也知道如何限制随机生成的整数之和.唯一的问题是满足N值中没有一个超出指定范围的条件. 例如generate_ints(n,total,low,high)应该生成n值数组,使得每个值都在低和高之间,并且总和加起来总和.任何
我看到其他帖子解决了类似的问题.我知道如何生成N个正整数.我也知道如何限制随机生成的整数之和.唯一的问题是满足N值中没有一个超出指定范围的条件.

例如generate_ints(n,total,low,high)应该生成n值数组,使得每个值都在低和高之间,并且总和加起来总和.任何指针/帮助将不胜感激.

eggenerate_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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读