How to generate numbers in range with specific average with Python?

后端 未结 6 583
感动是毒
感动是毒 2020-12-10 23:08

For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.

E

6条回答
  •  囚心锁ツ
    2020-12-10 23:48

    Not optimal in terms of covering the range as much as possible, but you can try this:

    def GenerateArr(count,minimum,maximum,average):
        arr = []
        diff = 1
        while len(arr) < count-1:
            if minimum <= average-diff and average+diff <= maximum:
                arr.append(average-diff)
                arr.append(average+diff)
                diff += 1
            else:
                arr.append(average)
                diff = 1
        if len(arr) < count:
            arr.append(average)
        return arr
    
    print GenerateArr(22,20,46,27)
    

提交回复
热议问题