一个小小的谜语:你有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])
是的,您可以使用subset-sum problem的动态规划解决方案检查可能的组合
只要解
subset_sum(hypothesis, sum(hypothesis) // 3)
相关问题 更多 >
编程相关推荐