我在寻找平衡分区问题here和here (problem 7)。平衡分区贪婪方法
该问题基本上要求将给定的数字数组分割成2个子集(S1和S2),使得数字之和的绝对差值为S1和S需要最小。有一件事我不明白的是为什么没有人提出贪婪的方法:
def balanced_partition(lst):
idx = 0
S1 = 0
S2 = 0
result_partition=[None]*len(lst)
while idx < len(lst):
new_S1 = S1 + lst[idx]
new_S2 = S2 + lst[idx]
if abs(new_S1 - S2) < abs(new_S2 - S1):
result_partition[idx] = 1
S1 = new_S1
else:
result_partition[idx] = 2
S2 = new_S2
idx += 1
print("final sums s1 = {S1} and s2 = {S2} ".format(S1=S1, S2=S2))
return result_partition
我的方法有什么问题?它似乎通过了我能想出的所有测试案例。
“似乎通过了大部分测试用例”。所以它失败了一些测试用例?这不是回答你的问题吗? –
大部分测试用例我的意思是我找不到反对贪婪方法的任何争论,我自己也无法(出现)/发现负面测试用例。编辑我的问题。 – kmad1729
你是如何搜索负面测试用例的?几乎每个排序的列表都是您的方法的最佳反例(例如:[1,2,3])。 –