python-3.x - 蛮力子集总和解决方案抛出“设置”对象不是下标错误

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

下面是我写的一个求和集问题的强力方法在以下语句中,由于出现“set object i s not subscriptable”错误,我无法打印“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))

最佳答案

出现此错误是因为使用S[i + 1:]中的possible_targets()试图选择set对象的特定部分,这是无序的,并且没有实现__getitem__()方法。
如果顺序重要,可以使用listlist(S)将集合转换为sorted(S)来解决此问题。

关于python-3.x - 蛮力子集总和解决方案抛出“设置”对象不是下标错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255102/

相关文章:

algorithm - 随机访问固定字母表中 3 个符号的排序集合的枚举

Java:检索 ArrayList 的随机不连续子列表(最有效的方法)

java - 通过调用另一个bean的方法来创建bean

eclipse - Robot框架和python selenium组合时的调试测试用例

python - 由于内核错误而无法使用 python 3

algorithm - 如何确定两个名称列表之间的对应关系?

python - 字典神奇地转换为在 nosetests 中设置

python - TesseractNotFoundError : tesseract is not installed or it's not in your path

python - 在python中处理包含标点编码的数据文件中的字符串

algorithm - 求解 ODE 算法的有限差分法