从范围生成均匀分布的数字列表

时间:2014-02-09 23:50:09

标签: python distribution

我之前已经看过这个问题,但我正在寻找一个有问题的答案:

考虑我有一个类似1-100的范围,我想生成一个列表,其中包含特定的步骤:numbers(1,100,5)。这将返回[1,25,50,75,100]。但是,我希望它返回[1,100,50,25,75][1,100,50,75,25]另一个例子是数字(1,10,10),它会给我类似[1,10,5,2,7,3,8,4,9]的内容。

这甚至可以吗?这样做的原因是能够在不从帧1到帧2到帧3等的情况下渲染图像序列。相反,我想渲染第一帧,最后一帧,中间帧,中间帧的中间,直到所有帧都被占用。

2 个答案:

答案 0 :(得分:1)

你的问题有点不明确,但这应该可以帮助你开始。

def numbers(first, last, count):
    nums = [first, last]
    width = last - first
    while len(nums) < count:
        width /= 2
        stepper = first
        while stepper < last:
            rounded = round(stepper)
            if rounded not in nums:
                nums.append(rounded)
                if len(nums) == count:
                    break
            stepper += width
    return nums

然后:

>>> numbers(0, 100, 5)
[0, 100, 50, 25, 75]
>>> numbers(0, 10, 10)
[0, 10, 5, 2, 8, 1, 4, 6, 9, 3, 7]
>>> numbers(0, 50, 50)
[0, 50, 25, 12, 38, 6, 19, 31, 44, 3, 9, 16, 22, 28, 34, 41, 47, 2, 5, 8, 11, 14, 17, 20, 23, 27, 30, 33, 36, 39, 42, 45, 48, 1, 4, 7, 10, 13, 15, 18, 21, 24, 26, 29, 32, 35, 37, 40, 43, 46]

基本算法如下:

  • 从包含两个端点的nums列表开始
  • width初始化为两个端点之间的距离
  • 然后,循环:
    • Halve width
    • 逐步完成firstfirst+widthfirst+2*width,...,last-widthlast,然后添加其中的任何一个nums 1}}到nums(因此,对于numbers(0, 100, 5),第一次循环迭代将尝试0,50和100,并且仅添加50,因为它尚未存在;第二次迭代将尝试0 ,25,50,75和100,只添加25和75)。
    • 如果nums中有足够的数字,我们就完成了
  • 返回nums

答案 1 :(得分:0)

好的,所以你想要的帧很奇怪,特别是因为第一个例子中的元素不是均匀分布的,例如。 100-75 = 25,75-50 = 25,50-25 = 25, 25-1 = 24

但是,如果我们假设你总是想要帧中的起始值和结束值,并希望将均匀间隔的值与最大值挂钩,那么我们可以这样做:

def numbers(start,stop,step=1):
    frame = [start]+range(y,stop,(start-stop)/(step-1))
    return frame

random模块包含shuffle()方法,该方法接收数组并将其就地

这意味着该功能变为:

from random import shuffle
def numbers(start,stop,step=1):
    frame = [start]+range(y,stop,(start-stop)/(step-1))
    shuffle(frame)
    return frame

给我们以下测试运行:

>>> numbers(1,100,5)
[100, 50, 75, 1, 25]
>>> numbers(1,10,10)
[1, 3, 10, 9, 6, 5, 8, 4, 7, 2]

原创(但错误的)答案

random模块包含shuffle()方法,该方法接收数组并将其就地

例如:

from random import shuffle
def numbers(start,stop,step=1):
    frame = range(start,stop,step)
    shuffle(frame)
    return frame

然后调用此函数:

>>> numbers(1,100,25)
[1, 51, 26, 76]
>>> numbers(1,100,25)
[76, 26, 1, 51]

请注意,根据range()函数,step值会重复添加到start,以便最终数组的格式为[start, start+1*step, start+2*step ... start + n*step],其中start+n*step 1}}小于stopstart+(n+1)*step大于stop