itertool and multiprocessing, How can I generate all possible combinations in Parallel

最后都变了- 提交于 2019-12-11 05:36:13

问题


I have the following code which generates all possible combination that produces a given sum (n). This code, however, takes very long for large numbers (n). Is there a way I can parallelize my code across multiple processors?

from itertools import combinations_with_replacement

def all_combination(numbers, n):
result = [seq for i in range(n, 0, -1) for seq in combinations_with_replacement(numbers,i) if sum(seq) == n]
return result

numbers = [1, 2, 3, 4, 5, 6]
n=700
print len(all_combination(numbers,n))

回答1:


from itertools import product
import math
import multiprocessing

def parallel_combination(i, limit):
    numbers = [1, 2, 3, 4, 5, 6]
    result=0
    for seq in combinations_with_replacement(numbers, i):
        if sum(seq) == limit:
            result+=1
    return result

def chunks(min_value, max_value):
    for i in range(max_value, min_value, -1):
        yield i

if __name__ == "__main__":
    max_value=610
    limit=610
    min_value=int(math.floor(float(limit/6)))
    pool = multiprocessing.Pool()
    n_processesor=32
    chunk_size=int((math.ceil(float((max_value-min_value))/n_processesor)))
    processes = pool.map(func=parallel_combination, limit, iterable=chunks(min_value,max_value), chunksize=chunk_size)
   final_result=0
   for process in processes:
        if process:
            final_result+=process
    print final_result


来源:https://stackoverflow.com/questions/42468136/itertool-and-multiprocessing-how-can-i-generate-all-possible-combinations-in-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!