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