簡體   English   中英

為什么不附加第一個元素

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

我正在嘗試打印子集總和問題的所有子集。 也就是說,從數組中打印出總和為給定數字的所有子集。 然而,在后來的事件中,子集似乎省略了最終答案中的前一兩個條目,這是為什么呢?

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]

請幫忙。

我建議使用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)

就這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM