[英]Find all combination that sum to N with multiple lists
鑒於 :
m
個列表( m
可以變化)。 arange()
。 想要 :
sum()
到N
的m-tuple(每個列表一個數字sum()
。 我有什么 :
我可以在靜態列表中找到所有組合。
import numpy as np for a in np.arange(0,1,0.01): for b in np.arange(0,1,0.01): for c in np.arange(0,1,0.01): for d in np.arange(0,1,0.01): if (a+b+c+d) == 1.0: print a,b,c,d
我也想找到一種最佳的計算方法。
正如評論中所討論的那樣,范圍都是相同的,我們應該使用整數。 這是一個非常好的方式。
而不是生成四個數字並測試它們是否加起來為10,而是產生三個數字,將區間[0,10]的分區定義為四個區間。 例如,當我們在(3,4,8)處進行切割時,我們添加端點0和10,那么我們就有邊界(0,3,4,8,10)。 相鄰邊界之間的差異是(3-0,4-3,8-4,10-8)=(3,1,4,2)。 這是四個數字加起來為10.這里是代碼:
n = 10
import itertools, operator
for cuts in itertools.combinations_with_replacement(range(n+1), 3):
combi = list(map(operator.sub, cuts + (n,), (0,) + cuts))
if max(combi) < n:
print(combi)
打印:
[0, 0, 1, 9]
[0, 0, 2, 8]
[0, 0, 3, 7]
[0, 0, 4, 6]
[0, 0, 5, 5]
[0, 0, 6, 4]
[0, 0, 7, 3]
[0, 0, 8, 2]
[0, 0, 9, 1]
[0, 1, 0, 9]
[0, 1, 1, 8]
[0, 1, 2, 7]
...
...
[7, 2, 0, 1]
[7, 2, 1, 0]
[7, 3, 0, 0]
[8, 0, 0, 2]
[8, 0, 1, 1]
[8, 0, 2, 0]
[8, 1, 0, 1]
[8, 1, 1, 0]
[8, 2, 0, 0]
[9, 0, 0, 1]
[9, 0, 1, 0]
[9, 1, 0, 0]
它非常高效,因為它可以非常直接地生成組合。 if max(combi) < n
僅過濾掉[0, 0, 0, 10]
if max(combi) < n
[0, 0, 0, 10]
, [0, 0, 10, 0]
, [0, 10, 0, 0]
和[10, 0, 0, 0]
。
這是你的原版,我的和@ Mijamo之間的速度比較,有100個數字,如你的例子:
drum: 21.027 seconds
Stefan: 0.708 seconds
Mijamo: 62.864 seconds
該測試的完整代碼:
import itertools, operator
from timeit import timeit
def drum(n):
out = []
for a in range(n):
for b in range(n):
for c in range(n):
for d in range(n):
if a + b + c + d == n:
out.append((a, b, c, d))
return out
def Stefan(n):
combinations = (map(operator.sub, cuts + (n,), (0,) + cuts)
for cuts in itertools.combinations_with_replacement(range(n+1), 3))
return [c for c in combinations if max(c) < n]
def Mijamo(n):
combinations = itertools.product(range(n), repeat=4)
return [tuple for tuple in combinations if sum(tuple) == n]
for func in drum, Stefan, Mijamo:
print '%6s: %6.3f seconds' % (func.__name__, timeit(lambda: func(100), number=1))
可以通過以下方式檢索所有組合:
combinations = itertools.product(np.arange(0,1,0.01), repeat = m)
https://docs.python.org/3.5/library/itertools.html#itertools.product
因為它是一個生成器,你可以創建一個新的生成器,以這種方式返回總和為n的tupples
results = (tuple for tuple in combinations if sum(tuple) == N)
如何使用itertools中的“product”獲取所有可能的m-length元組。 然后你只需要通過元組和= = N的條件進行過濾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.