下面是我写的一个求和集问题的强力方法在以下语句中,由于出现“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__()
方法。
如果顺序重要,可以使用list
或list(S)
将集合转换为sorted(S)
来解决此问题。
关于python-3.x - 蛮力子集总和解决方案抛出“设置”对象不是下标错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255102/