Brute Force Subset Sum Solution抛出'set'对象不是下标错误

问题描述 投票:0回答:1

以下是我编写的求和集问题的暴力破解方法。在以下语句中出现“设置对象不可下标”错误时,无法打印“ BFI_Subset_Sum(S,k)”:“对于for可能性_targets(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))

以下是我编写的求和集问题的暴力破解方法。在出现以下语句时,出现“设置对象不可下标”错误,因此无法打印“ BFI_Subset_Sum(S,k)”:...

python-3.x algorithm set brute-force subset-sum
1个回答
0
投票

之所以出现此错误,是因为通过在S[i + 1:]中使用possible_targets(),您正在尝试选择set对象的特定部分,该对象是无序的,并且没有实现set方法。您可以通过按顺序使用__getitem__()__getitem__()将集合转换为list来解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.