一个小谜语:你有6包6,12,14,15,23和29张牌。有些包有猪卡,有些包有狐狸卡。如果你删除一个包,猪的卡是狐狸卡的两倍。你必须删除哪个数据包?
我需要迭代数据包,从列表中删除它并在可能的子组上创建/置换以找到正确的组合。
以下代码解决了这个问题,但我反复取得了成功,而且我确信它有一种更高效,更优雅的方式来编写它。请告诉我!
#!/usr/bin/env python3
from itertools import permutations
packets = [6, 12, 14, 15, 23, 29]
for position, packet in enumerate(packets):
hypothesis = list(packets)
del(hypothesis[position])
# the next conditional is not really needed,
# only use it to save some operations
if sum(hypothesis) % 3 == 0:
for item in permutations(hypothesis, 5):
if sum(item[:2]) * 2 == sum(item[2:]):
print(item[:2], "and", item[2:], "removed: ", packets[position])
答案 0 :(得分:0)
是的,您可以使用subset-sum problem的动态编程解决方案检查可能的组合。
只需解决subset_sum(hypothesis, sum(hypothesis) // 3)