Benard Benard - 19 days ago 6
Python Question

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?

Example: GenerateNums(start=1, stop=5, nums=10)

Expected output: [1,1,2,2,3,3,4,4,5,5] i.e each number has an almost equal count

Answer

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.

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]
Comments