例如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 npdef 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_arrnew_arr = sampler (2872,30000,[5,15])print "Generated random array is :"print new_arrprint "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: 2872Max of array: 15min of array: 5and it sums up to 30000总结
以上是内存溢出为你收集整理的在一个范围内生成N个正整数,在python中累加总数全部内容,希望文章能够帮你解决在一个范围内生成N个正整数,在python中累加总数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)