python中从列表中获取可能和的最有效方法

python中从列表中获取可能和的最有效方法,python,methods,knapsack-problem,Python,Methods,Knapsack Problem,类似于背包问题。 如果我有 list = [5,7,9,12,6] targetValue = 15 既然6+9=15,最有效的方法是什么 [6,9] python是否有针对此类问题的内置方法?这里有一个快速解决方案。但是,请注意,如果列表中包含重复的值,则可能会得到重复的解决方案 from itertools import * s = [5, 7, 9, 12, 6] m = 15 c = chain(*[combinations(s, i) for i in range(len(s)

类似于背包问题。 如果我有

list = [5,7,9,12,6]
targetValue = 15
既然6+9=15,最有效的方法是什么

[6,9]

python是否有针对此类问题的内置方法?

这里有一个快速解决方案。但是,请注意,如果列表中包含重复的值,则可能会得到重复的解决方案

from itertools import *

s = [5, 7, 9, 12, 6]
m = 15

c = chain(*[combinations(s, i) for i in range(len(s)+1)])
r = [n for n in c if sum(n) == m]

print r
下面是一个更复杂的版本,用于处理列表中的重复值:

from itertools import *
from collections import *

s = [5, 7, 9, 12, 6]
m = 15

c = Counter(s)
u = list(c)
ul = len(u)
t = [c[x] for x in u]
p = product(*[xrange(i+1) for i in t])
e = ([a for b in [[u[i]] * x[i] for i in range(ul)] for a in b] for x in p)
r = [n for n in e if sum(n) == m]

print r

不,它没有任何内置的功能。