的最佳方式范围分成n个相等的范围在Python

问题描述:

我具有范围N元件的总数目和若干块nb的最佳方式范围分成n个相等的范围在Python

我要划分Nnb最佳可能等于范围,只用起始号码和结束号码。因此,例如,N=24nb=5应该输出:

0,5 5,10 10,15 15,20 20,24 

虽然N=28nb=5应该输出:

0,5 5,10 10,16 16,22 22,28 (the rest of `N/nb` division is equally distributed on the 3 last subranges) 

基于一个评论,我有这样的方法:

def partition(lst, n): 
    division = len(lst)/n 
    return [lst[round(division * i):round(division * (i + 1))] for i in range(n)] 

def ranges(N, nb): 
    return ["{},{}".format(r.start, r.stop) for r in partition(range(N), nb)] 

>>> ranges(28, 5) 
['0,6', '6,11', '11,17', '17,22', '22,28'] 

有一个更好的方法来做到这一点?

+1

这有点类似于这个问题:https://*.com/q/2659900/270986 –

这无疑是简单直接计算的起始和终止数字,而不是切片一个range对象,让他们:

def ranges(N, nb): 
    step = N/nb 
    return ["{},{}".format(round(step*i), round(step*(i+1))) for i in range(nb)] 

这不是比你的代码更高效,它可能看起来是因为切一range对象只需要O(1)时间,所以您现有的代码已经渐近最优。我的版本可能会提高性能的一些常数,但它可能很小。我认为我的版本也更清晰,这可能比可能出现的性能变化更重要。