【问题标题】:Generate all combinations of N items into two bags, whereby each item is in one or zero bags将 N 个项目的所有组合生成到两个袋子中,其中每个项目在一个或零个袋子中
【发布时间】:2020-02-22 08:17:49
【问题描述】:

我需要编写一个生成器,它返回每个项目的排列,使得每个项目都在两个不同的袋子中的一个或没有。每个组合应作为两个列表的元组给出,第一个是 bag1 中的项目,第二个是 bag2 中的项目。

我编写了以下代码,但它未能通过一个测试用例。它说我的实现比正确答案有更多的安排。第二个测试用例通过。我看不到测试用例正在使用哪些项目,但我尝试了一些值,它似乎有效。有人可以解释一下有什么问题吗?

我基本上在做的是删除数组中的第一项,然后递归调用函数其余部分。然后,我为递归返回的每个排列生成所有可能的排列,其中包含先前删除的项目(不添加它,仅将其添加到第一个袋子,仅将其添加到第二个袋子)。

def yieldAllCombos(items):
    """
        Generates all combinations of N items into two bags, whereby each 
        item is in one or zero bags.

        Yields a tuple, (bag1, bag2), where each bag is represented as a list 
        of which item(s) are in each bag.
    """
    # Your code here
    if (items == []):
        yield ([], [])
    else:
        item = items[0]
        for result in yieldAllCombos(items[1:]):
            yield (result[0], result[1])
            yield (result[0] + [item], result[1])
            yield (result[0], result[1] + [item])

【问题讨论】:

  • 输出列表中的项目与items 列表中的原始顺序相反。您可以尝试按照输入顺序而不是使用yield ([item] + result[0], result[1])yield (result[0], [item] + result[1]) 使它们符合评分者的期望。
  • 你是对的。现在它起作用了。谢谢;)

标签: python algorithm generator


【解决方案1】:

正如@blhsing 建议的那样,将项目设置为列表中的第一个元素可以解决问题。

def yieldAllCombos(items):
    """
        Generates all combinations of N items into two bags, whereby each 
        item is in one or zero bags.

        Yields a tuple, (bag1, bag2), where each bag is represented as a list 
        of which item(s) are in each bag.
    """
    # Your code here
    if (items == []):
        yield ([], [])
    else:
        item = items[0]
        for result in yieldAllCombos(items[1:]):
            yield (result[0], result[1])
            yield ([item] + result[0], result[1])
            yield (result[0], [item] + result[1])

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多