我正在尝试解决Hackerrank问题非除数子集,如下所述:
我尝试了以下解决方案(对于示例测试用例有效):
# The lines below are for Hackerrank submissions
# n, k = map(int, raw_input().strip().split(' '))
# a = map(int, raw_input().strip().split(' '))
n = 4
k = 3
a = [1, 7, 2, 4]
while True:
all_pairs = [(a[i],a[j]) for i in range(len(a)) for j in range(i+1,len(a))]
tested_pairs = {pair: (pair[0] + pair[1]) % k != 0 for pair in all_pairs}
disqualified_pairs = {key: value for key, value in tested_pairs.iteritems() if not value}.keys()
if not disqualified_pairs:
break
occurrences = list(sum(disqualified_pairs, ()))
counts = map(lambda x: occurrences.count(x), a)
index_remove = counts.index(max(counts))
a.remove(index_remove)
print len(a)
我试图识别“冲突”对,并删除出现最频繁的
a
元素,直到没有“冲突”对为止。然而,大多数测试用例都会出现“运行时错误”。
可以假设上述算法在只需要删除一个数字(数字2)的简单情况下有效,但在更复杂的测试用例中失败。有人能看出问题出在哪里吗?
更新
根据poke的建议,测试k = 2
和a = [1, 2, 3]
,我做了以下修改:
n = 4
k = 2
a = [1, 2, 3]
while True:
all_pairs = [(a[i],a[j]) for i in range(len(a)) for j in range(i+1,len(a))]
disqualified_pairs = [pair for pair in all_pairs if (pair[0] + pair[1]) % k == 0]
if not disqualified_pairs:
break
offending_numbers = sum(disqualified_pairs, ()) # 'Flatten' the disqualified pairs into a single list
counts = {el: offending_numbers.count(el) for el in set(offending_numbers)} # Count occurrences of each offending number
number_to_remove = max(counts, key=counts.__getitem__)
a.remove(number_to_remove)
print len(a)
得到的a
是[2, 3]
,包含两个元素,符合预期。我还检查了它是否仍适用于原始示例。但是,在某些测试用例中仍然会出现“分段错误”:
a = [1, 7, 2, 4, 6, 3]
,在这种情况下,算法似乎正确地删除了两个数字(2
和3
)。也许“运行时错误”与Hackerrank解决方案检查器有关? - Kurt Peekk = 2
和a = [1, 2, 3]
。 - poke