你的問題有點不明確,但這應該有助於你開始。
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
的距離在兩者之間的列表端點
- 然後,循環:
- 減半
width
- 步驟通過
first
,first+width
,first+2*width
,...,last-width
,last
,並添加這些之中取其是不是已經在nums
到nums
(所以,對於numbers(0, 100, 5)
,第一循環迭代將嘗試0 ,50和100,並且只增加了50個,因爲這還沒有出現;第二次迭代將嘗試0,25,50,75和100,並且只添加25和75)。
- 如果我們
nums
有足夠的數量,我們就大功告成了
- 返回
nums
名單你有不匹配的步長跳躍你的要求,它使你的問題很混亂。 – 2014-02-10 00:04:41