简体   繁体   English

为什么不附加第一个元素

[英]Why aren't the first elements being appended

I am trying to print all subsets for the subset sum problem.我正在尝试打印子集总和问题的所有子集。 That is, print all subsets from an array which sum to a given number.也就是说,从数组中打印出总和为给定数字的所有子集。 However, in the later occurrences, the subsets seem to omit the first one or two entries from the final answer, why is that??然而,在后来的事件中,子集似乎省略了最终答案中的前一两个条目,这是为什么呢?

import numpy as np
def calcSubsets(arr, i, target, current, dp):
    if(i==0 and target != 0 and dp[0][target]):
        current.append(arr[i])
        print(current)
        current.clear()
        return
    if(i==0 and target ==0):
        print(current)
        current.clear() 
        return
    if(dp[i-1][target]):
        temp = []
        temp = current
        calcSubsets(arr, i-1, target, temp, dp)
    if(target >= arr[i] and dp[i-1][target-arr[i]]):
        current.append(arr[i])
        calcSubsets(arr,i-1,target-arr[i], current, dp)


def printAll(arr, n, target):
    if(n==0 or target<0):
        return
#    for i in range(0,n):
#        dp[i][0] = True
    for i in dp:
        i[0] = True
        i[1:] = False
    if(arr[0]<=target):
        dp[0][arr[0]] = True
    for i in range(1,n):
        for j in range(0,target+1):
            dp[i][j] = (dp[i-1][j] or dp[i-1][j-arr[i]]) if (arr[i] <= j) else dp[i-1][j]

    if(not(dp[n-1][target])):
        print("INFEASIBLE")
        return

    current = []
    calcSubsets(arr,n-1,target, current, dp)

#arr = fa.toArray('purple.txt')
arr = [1,2,3,4,5,6]
target = 15
n = len(arr)
dp = np.empty((n,target+1), dtype=bool)
printAll(arr, n, target)


Expected output

[5,4,3,2,1]
[6,4,3,2]
[6,5,3,1]
[6,5,4]

Actual Output

[5,4,3,2,1]
[6,4,3,2]
[5,3,1]
[6,5,4]

Please help.请帮忙。

I suggest complete rewrite of the code, with use of itertools :我建议使用itertools完全重写代码:

# first we grab powerset() from 
# https://docs.python.org/3/library/itertools.html#itertools-recipes
from itertools import chain, combinations
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 range(len(s)+1))

arr = [1,2,3,4,5,6]
target = 15
# now we filter out subsets with wrong sum
for t in powerset(arr):
    if sum(t) == target:
        print(t)

That's all.就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM