Python 将N个项目的所有组合生成两个袋子,其中每个项目位于一个或零个袋子中

Python 将N个项目的所有组合生成两个袋子,其中每个项目位于一个或零个袋子中,python,algorithm,generator,Python,Algorithm,Generator,我需要编写一个生成器,返回每一个项目的安排,使每个项目都在一个或两个不同的包没有。每个组合应作为两个列表的元组给出,第一个列表是bag1中的项目,第二个列表是bag2中的项目 我编写了以下代码,但其中一个测试用例失败。它说我的实施有比正确答案更多的安排。第二个测试用例通过。我看不出测试用例正在使用哪些项,但我尝试了一些值,它似乎起了作用。有人能给我解释一下怎么了吗 基本上,我要做的是删除数组中的第一项,并递归调用函数和其余项。然后,对于递归返回的每个安排,我会给出所有可能的安排,包括之前移除的项

我需要编写一个生成器,返回每一个项目的安排,使每个项目都在一个或两个不同的包没有。每个组合应作为两个列表的元组给出,第一个列表是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])

正如@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])

正如@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])

输出列表中的项目与
项目
列表中的原始顺序相反。您可以尝试使用
收益率([item]+result[0],result[1])
收益率(result[0],[item]+result[1])
使他们按照输入顺序进行操作,以符合评分员的期望。您是对的。现在它起作用了。谢谢;)输出列表中的项目与
项目
列表中的原始顺序相反。您可以尝试使用
收益率([item]+result[0],result[1])
收益率(result[0],[item]+result[1])
使他们按照输入顺序进行操作,以符合评分员的期望。您是对的。现在它起作用了。谢谢;)