蛮力子集总和解决方案引发“设置”对象不是下标错误

时间:2019-10-06 07:21:58

标签: python-3.x algorithm set brute-force subset-sum

以下是我编写的求和集问题的暴力破解方法。在以下语句中出现“设置对象不可下标”错误时,无法打印“ BFI_Subset_Sum(S,k)”: “对于“可能的目标”中的“可能的目标(S [i + 1:],大小-1):”

我如何精确打印此功能并获得输出?

这是我的代码,谢谢:

# define Set object and attributes
class Set:
    elements = {}
    sum = {}


# initializing empty sets for sums and elements
empty_set = Set()
empty_set.sum = 0
empty_set.elements = {}

# set whos subsets will be evaluated
S = {3, 5, 3, 9, 18, 4, 5, 6}

# target value
k = 9


def BFI_Subset_Sum(S, k):
    subsets = {}
    size = 1

    while size <= len(S):
        for possible_target in possible_targets(S, size):
            if sum(possible_target) == k:
                subsets.append(possible_target)
                print(possible_target)
        size += 1
        print(subsets)
    return subsets


def possible_targets(S, size):
    if len(S) <= 0 or size <= 0:
        print("no subset sums to the target value")
    else:
        for i, num in enumerate(S):
            for possible_target in possible_targets(S[i + 1:], size - 1):
                yield [num] + possible_target


print(BFI_Subset_Sum(S, k))

0 个答案:

没有答案