根据@Alin Purcaru和@amit的回答,我编写了代码(Python 3.1)。经过测试,它具有线性性能(对于项目数量和块数量都是如此,因此最终为O(N * M))。我避免每次对列表进行排序,而是在字典中保留每个块的当前值总和(在块数较大时可能不太实用)。
import time, random
def split_chunks(l, n):
"""
Splits list l into n chunks with approximately equals sum of values
see https://dev59.com/Kmw15IYBdhLWcg3wD3jp
"""
result = [[] for i in range(n)]
sums = {i:0 for i in range(n)}
c = 0
for e in l:
for i in sums:
if c == sums[i]:
result[i].append(e)
break
sums[i] += e
c = min(sums.values())
return result
if __name__ == '__main__':
MIN_VALUE = 0
MAX_VALUE = 20000000
ITEMS = 50000
CHUNKS = 256
l =[random.randint(MIN_VALUE, MAX_VALUE ) for i in range(ITEMS)]
t = time.time()
r = split_chunks(l, CHUNKS)
print(ITEMS, CHUNKS, time.time() - t)
因为我们有这个能力,所以同样的代码在PHP 5.3中(比Python 3.1慢2-3倍):
function split_chunks($l, $n){
$result = array_fill(0, $n, array());
$sums = array_fill(0, $n, 0);
$c = 0;
foreach ($l as $e){
foreach ($sums as $i=>$sum){
if ($c == $sum){
$result[$i][] = $e;
break;
}
}
$sums[$i] += $e;
$c = min($sums);
}
return $result;
}
define('MIN_VALUE',0);
define('MAX_VALUE',20000000);
define('ITEMS',50000);
define('CHUNKS',128);
$l = array();
for ($i=0; $i<ITEMS; $i++){
$l[] = rand(MIN_VALUE, MAX_VALUE);
}
$t = microtime(true);
$r = split_chunks($l, CHUNKS);
$t = microtime(true) - $t;
print(ITEMS. ' ' . CHUNKS .' ' . $t . ' ');