集合中加权元素的组合,其中加权和等于固定整数(在python中)

时间:2011-11-04 14:02:15

标签: python combinations knapsack-problem

我想找到一组中加权元素的所有可能组合,其权重之和完全等于给定的权重W

假设我想从{ 'A', 'B', 'C', 'D', 'E' }weights = {'A':2, 'B':1, 'C':3, 'D':2, 'E':1}中选择k W = 4中的k个元素。

然后这会产生: ('A','B','E') ('A','D') ('B','C') ('B','D','E') ('C','E')

我意识到蛮力的方式是找到给定集合的所有排列(用itertools.permutations)并用加权和W拼接出前k个元素。但是我正在处理至少20个每套元素,这在计算上是昂贵的。

我认为使用背包的变体会有所帮助,只考虑重量(不是值),重量之和必须等于到W(不低于)。

我想在python中实现它,但任何cs理论提示都会有所帮助。优雅的奖励点!

3 个答案:

答案 0 :(得分:3)

循环遍历所有 n !排列太昂贵了。而是生成所有2 ^ n 子集。

from itertools import chain, combinations

def weight(A):
    return sum(weights[x] for x in A)

# Copied from example at http://docs.python.org/library/itertools.html
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in xrange(len(s) + 1))

[x for x in powerset({'A', 'B', 'C', 'D', 'E'}) if weight(x) == W]

产量

[('A', 'D'), ('C', 'B'), ('C', 'E'), ('A', 'B', 'E'), ('B', 'E', 'D')]

可以将列表理解的返回部分更改为tuple(sorted(x)),或将list中的powerset调用替换为sorted,将其转换为已排序的元组

答案 1 :(得分:1)

这些套装中的商品数量是否有上限?如果你这样做,并且它最多约为40,那么"meet-in-the-middle" algorithm中描述的Wikipedia page on Knapsack可能非常简单,并且复杂程度明显低于蛮力计算。

注意:使用比Python dict更高效的内存数据结构,这也适用于更大的集合。一个有效的实现应该可以轻松处理大小为60的集合。

以下是一个示例实现:

from collections import defaultdict
from itertools import chain, combinations, product

# taken from the docs of the itertools module
def powerset(iterable):
     "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
     s = list(iterable)
     return chain.from_iterable(combinations(s, r) for r in xrange(len(s) + 1))

def gen_sums(weights):
    """Given a set of weights, generate a sum --> subsets mapping.

    For each posible sum, this will create a list of subsets of weights
    with that sum.

    >>> gen_sums({'A':1, 'B':1})
    {0: [()], 1: [('A',), ('B',)], 2: [('A', 'B')]}
    """
    sums = defaultdict(list)
    for weight_items in powerset(weights.items()):
        if not weight_items:
            sums[0].append(())
        else:
            keys, weights = zip(*weight_items)
            sums[sum(weights)].append(keys)
    return dict(sums)

def meet_in_the_middle(weights, target_sum):
    """Find subsets of the given weights with the desired sum.

    This uses a simplified meet-in-the-middle algorithm.

    >>> weights = {'A':2, 'B':1, 'C':3, 'D':2, 'E':1}
    >>> list(meet_in_the_middle(weights, 4))
    [('B', 'E', 'D'), ('A', 'D'), ('A', 'B', 'E'), ('C', 'B'), ('C', 'E')]
    """
    # split weights into two groups
    weights_list = weights.items()
    weights_set1 = dict(weights_list[:len(weights)//2])
    weights_set2 = dict(weights_list[len(weights_set1):])

    # generate sum --> subsets mapping for each group of weights,
    # and sort the groups in descending order
    set1_sums = sorted(gen_sums(set1).items())
    set2_sums = sorted(gen_sums(set2).items(), reverse=True)

    # run over the first sorted list, meanwhile going through the
    # second list and looking for exact matches
    set2_sums = iter(set2_sums)
    try:
        set2_sum, subsets2 = set2_sums.next()
        for set1_sum, subsets1 in set1_sums:
            set2_target_sum = target_sum - set1_sum
            while set2_sum > set2_target_sum:
                set2_sum, subsets2 = set2_sums.next()
            if set2_sum == set2_target_sum:
                for subset1, subset2 in product(subsets1, subsets2):
                    yield subset1 + subset2
    except StopIteration: # done iterating over set2_sums
        pass

答案 2 :(得分:0)

有效地执行此操作的技巧是使用前k个项创建具有相同权重的元素集。

从k = 0的空集开始,然后使用k-1的组合为k创建组合。除非您可以使用负权重,否则您可以修剪总重量大于W的组合。

以下是使用您的示例的方式:

梳子[k,w]是使用前k个元素具有总重量w的元素集合 支架用于套装。
S + e是通过将元素e添加到S的每个成员而创建的集合集。

comb[0,0]={}
comb[1,0]={comb[0,0]}
comb[1,2]={comb[0,0]+'A'}
comb[2,0]={comb[1,0]}
comb[2,1]={comb[1,0]+'B'}
comb[2,2]={comb[1,2]}
comb[2,3]={comb[1,2]'B'}
comb[3,0]={comb[2,0]}
comb[3,1]={comb[2,1]}
comb[3,2]={comb[2,2]}
comb[3,3]={comb[2,3],comb[2,0]+'C'}
comb[3,4]={comb[2,3]+'C'}
comb[4,0]={comb[3,0]}
comb[4,1]={comb[3,1]}
comb[4,2]={comb[3,2],comb[3,0]+'D'}
comb[4,3]={comb[3,3],comb[3,1]+'D'}
comb[4,4]={comb[3,4],comb[3,2]+'D'}
comb[5,0]={comb[4,0]}
comb[5,1]={comb[4,1],comb[4,0]+'E'}
comb[5,2]={comb[4,2],comb[4,1]+'E'}
comb[5,3]={comb[4,3],comb[4,2]+'E'}
comb[5,4]={comb[4,4],comb[4,3]+'E'}

答案是梳[5,4],简化为:

{
  {{'B'}+'C'},
  {{'A'}+'D'},
  {
    {{'A'}+'B'},
    {'C'},
    {'B'}+'D'             
  }+'E'
}

给予所有组合。