[英]generate numbers between min and max with equal counts
I have a minimum value and maximum value, I'd like to generate a list of numbers between them such that all the numbers have equal counts. 我有一个最小值和最大值,我想在它们之间生成一个数字列表,以便所有数字都具有相等的计数。 Is there a numpy function or any function out there? 是否有numpy函数或任何函数?
Example: GenerateNums(start=1, stop=5, nums=10) 示例:GenerateNums(start = 1,stop = 5,nums = 10)
Expected output: [1,1,2,2,3,3,4,4,5,5] ie each number has an almost equal count 预期输出:[1,1,2,2,3,3,4,4,5,5]即每个数字的计数几乎相等
Takes "almost equal" to heart -- the difference between the most common and least common number is at most 1. No guarantee about which number is the mode. 几乎“等于”心脏-最常见和最不常见的数字之间的差异最大为1。无法保证模式是哪个数字。
def gen_nums(start, stop, nums):
binsize = (1 + stop - start) * 1.0 / nums
return map(lambda x: int(start + binsize * x), xrange(nums))
gen_nums(1, 5, 10)
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
There is a numpy function: 有一个numpy函数:
In [3]: np.arange(1,6).repeat(2)
Out[3]: array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
For almost equal counts, you can sample from a uniform distribution. 对于几乎相等的计数,您可以从均匀分布中采样。 numpy.random.randint
does this: numpy.random.randint
这样做:
>>> import numpy as np
>>> np.random.randint(low=1, high=6, size=10)
array([4, 5, 5, 4, 5, 5, 2, 1, 4, 2])
To get these values in sorted order: 要按排序顺序获取这些值:
>>> sorted(np.random.randint(low=1, high=6, size=10))
[1, 1, 1, 2, 3, 3, 3, 3, 5, 5]
This process is just like rolling dice :) As you sample more times, the counts of each value should become very similar: 这个过程就像掷骰子一样:)随着采样次数的增加,每个值的计数应该变得非常相似:
>>> from collections import Counter
>>> Counter(np.random.randint(low=1, high=6, size=10000))
Counter({1: 1978, 2: 1996, 3: 2034, 4: 1982, 5: 2010})
For exactly equal counts: 对于完全相等的计数:
>>> range(1,6) * 2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> sorted(range(1,6) * 2)
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
def GenerateNums(start=1, stop=5, nums=10):
result = []
rep = nums/(stop - start + 1 )
for i in xraneg(start,stop):
for j in range(rep):
result.append(i)
return result
def GenerateNums(start=0,stop=0,nums=0,result=[]):
assert (nums and stop > 0), "ZeroDivisionError"
# get repeating value
iter_val = int(round(nums/stop))
# go through strt/end and repeat the item on adding
[[result.append(x) for __ in range(iter_val)] for x in range(start,stop)]
return result
print (GenerateNums(start=0, stop=5, nums=30))
>>> [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.