Python

时间:2017-09-19 20:45:07

标签: python combinations itertools

Itertool.combination代码为我提供了目标值的所有组合 我有一个数组

a=[1,1,2,-2,-4] target =0

输出我来自:

Itertools.combination is: [(2, -2), (1, 1, -2), (1, 1, 2, -4)].

但问题是: - 一旦使用了数字,就不应该重复。 所需输出: - [(2,-2)] #As 2,-2对网络为0.代码不应再次使用2来求和:1,1,2并用-4表示关闭。 [我不希望数字在其中一个中使用后重复。]

# Reference code:-

    import itertools
    import numpy as np

    def subset_sum(target, numbers):

        array_num=np.array(numbers)
        for size in xrange(1, len(array_num) + 1):
             for c in itertools.combinations(array_num, size):
                 if sum(c) == target:
                   temp_var.append(c)
                   print "Length of array is ",len(array_num)

        return temp_var

    numbers=[1,1,2,-2,-4]
    target=0
    output=subset_sum(numbers)
    print output

1 个答案:

答案 0 :(得分:0)

使用此:

concat = lambda i,j: list(i if type(i) is list else [i])+list(j if type(j) is list else [j])
reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x]) for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), [[[],filter( lambda x:sum(x)==target,list(itertools.combinations(a,u)))] for u in range(2,len(a)+1)]))

<强>输出:

>>> concat = lambda i,j: list(i if type(i) is list else [i])+list(j if type(j) i
s list else [j])
>>> a=[1,1,2,-2,-4]
>>> target=0
>>> reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x])
for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), [filter( lambda
x:sum(x)==target,list(itertools.combinations(a,u))) for u in range(2,len(a))]))
(2, -2)
>>> a=[5,1,3,-4,-5]
>>> reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x])
for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), [filter( lambda
x:sum(x)==target,list(itertools.combinations(a,u))) for u in range(2,len(a))]))
[(5, -5), (1, 3, -4)]
>>> a=[1,-1,2,-2,-4]
>>> reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x])
 for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), [filter( lambda
x:sum(x)==target,list(itertools.combinations(a,u))) for u in range(2,len(a))]))
[(1, -1), (2, -2)]
>>>
  

编辑:这是因为他后来comment

改变了他的意图
f=lambda x:tuple(map(lambda x:a[x],x)) if type(x)==tuple else map(lambda x:f(x),x)
f(reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x]) for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), [filter(lambda x:sum(f(x))==target,list(itertools.combinations(range(0,len(a)),u))) for u in range(0,len(a)+1)])))

这并不排除不同指数的已使用值:

>>> a=[21197595.75,11885337.56,-11885337.56,-11885337.56,-9312258.19]
>>> f(reduce(lambda x,y: x if any([u in j for j in (x if type(x) is list else [x
]) for u in y]) else concat(x,y), reduce(lambda x,y: concat(x,y), concat([filter
(lambda x:sum(f(x))==target,list(itertools.combinations(range(0,len(a)),u))) for
 u in range(2,len(a)+1)],[]))))
[(11885337.56, -11885337.56), (21197595.75, -11885337.56, -9312258.19)]
>>>