在python中使用递归函数查找对象列表的组合需要时间

时间:2018-02-20 19:19:53

标签: python numpy

我想找到sum等于target的第一个组合对象。并结束这个功能。

def subset_sum_batches(batches, target, partial=[]):
    qty_sum = sum([q.qty for q in partial]) 
    if qty_sum  == target:      # check if the partial sum is equals to target
        return partial
    if qty_sum >= target:       # if sum is greater than quantity continue
        return  False   

    for i in range(len(batches)):
        n = batches[i]
        remaining = batches[i+1:]
        result_batches=subset_sum_batches(remaining, target, partial+[n])
        if result_batches:
             return result_batches
    return False

参数 -

批次是对象列表

目标是与对象数量之和匹配的数量

如果我的对象列表包含少于20到30个对象,则此程序可以正常工作。但在实际情况中,对象列表的长度为1000到2000.然后找到组合需要花费太多时间。

需要帮助来改进代码。

1 个答案:

答案 0 :(得分:0)

我通过使用循环检查了这个问题并检查记录的总和是否大于目标,然后找到实现目标的数字在下一个对象中,如果是,则继续循环,否则中断并获取新对象。为了组合。

def subset_sum_batches(batches, target):
    partial=[]
    diff=0.0
    for i,start in enumerate(batches):
        if start.qty >target:
            continue
        partial=[start]
        remaining=batches[i+1:]
        if sum([q.qty for q in partial]) == target: # check if the partial sum is equals to target
            return partial
        for j,next in enumerate(remaining):
                partial.append(next)
                qty_sum = sum([q.qty for q in partial])     
                if qty_sum  == target:      # check if the partial sum is equals to target
                return partial
                if qty_sum >= target:       # if sum is greater than quantity continue
                    diff = qty_sum - next.qty
                    partial.pop()
                    flag=True
                    if not any([ diff < q.qty for q in remaining[j:]]):
                    break
        if flag and diff:
            if not any([ diff < q.qty for q in batches[i:]]):
                break
    return []