【问题标题】:split a list permuting over all possible sublists拆分一个列表,排列所有可能的子列表
【发布时间】:2017-12-11 22:46:17
【问题描述】:

一个小谜语:你有六包 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])

【问题讨论】:

    标签: python permutation


    【解决方案1】:

    是的,您可以使用subset-sum problem 的动态编程解决方案检查可能的组合。

    只要解决subset_sum(hypothesis, sum(hypothesis) // 3)

    【讨论】:

      猜你喜欢
      • 2015-06-21
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2017-11-26
      • 1970-01-01
      相关资源
      最近更新 更多