生成给定某个产品的列表的所有子集而不迭代整个powerset? (蟒蛇)

问题描述:

可能重复:
Finding all possible combinations of numbers to reach a given sum生成给定某个产品的列表的所有子集而不迭代整个powerset? (蟒蛇)

我不想因为它输出的顺序,我不想要的东西用Itertools不能使用(我需要能够评估组合发生器试图输出什么,以决定是否要继续沿着该分支行进)。

例如,假设我有一个列表[1,2,3,4,5],并且我想输出具有完整产品< = 12的组合,而不会浪费迭代。如果我生成[1,2,3],这很好,因为1 * 2 * 3 = 6。但是如果我尝试[1,2,3,4],然后1 * 2 * 3 * 4 = 24,并且这大于12,所以我甚至不会打扰到[1,2,3,5]或[1,2,4,5]等等。

当前的尝试:

from operator import mul 

mylist=[1,2,3,4,5] 
limit=12 

def productOK(mylist): #but this can be any conditional, theoretically 
    if reduce(mul, mylist) > limit: 
     return False 
    return True 


def generateValidSubsets(mylist): 
    for r in range(1,len(mylist)+1): 
     start=mylist[:r] 
     if productOK(start)==False: break 
     #not sure how to recombine in the right order otherwise 
     yield start 



for combo in generateValidSubsets(mylist): 
    print combo 

我要去哪里错了?

+0

所以......你是否试图用循环来实际编码? – Marcin 2012-04-18 13:57:49

+1

是的,但我不知道正确的方式递归地拆分列表,并以正确的顺序看待事情 – AOAOne 2012-04-18 13:59:21

+0

@Marcin我试图提前停止,如果它正在走下一条糟糕的道路,没有跳过任何可能的好路径。例如,在itertools中,如果我要提前打破循环,我可能会错过其他长度有效的组合,只是因为它们以较高的数字开头 – AOAOne 2012-04-18 14:00:47

我强烈建议您切换到递归实现。这将让您更轻松地实施裁员:

def subs(target, universe, currentsubs, currentproduct, goodsubs): 
    first_from_universe_not_in_currentsubs = # an exercise for the reader 
    newsubs = [first_from_universe_not_in_currentsubs] + currentsubs 
    newproduct = currentproduct * first_from_universe_not_in_currentsubs 
    if newproduct == target: 
     return goodsubs + [newsubs] 
    elif newproduct > target: 
     return goodsubs 
    else: 
     return subs(target, universe, newsubs, newproduct, goodsubs) 

subs(12, [1,2,3,4,5], [], 0, []) 

即使你填空上面,它可能不是很正确,但它确实表明,你怎么能实现晋级。

+0

我不认为这是做我想做的事情(不能说出大多数这些变量的目的是什么),我不认为“首先从宇宙不在当前的潜艇”是特别有效的,如果它需要重新扫描整个列表。 – AOAOne 2012-04-18 14:35:24

+0

@AOAOne如果你不能理解代码,那就暗示你正在寻找某人向你展示代码。 – Marcin 2012-04-18 14:36:55

+0

我在说我不认为这是在做我在问什么。如果新产品等于目标,为什么它很重要?这与我的问题无关 - 我只关心它是否大于。但是,如果它大于,则返回“goodsubs”(我认为这意味着“当前的良好解决方案”)。否则,我不确定哪些电流子以及为什么需要“首先来自宇宙不在当前的潜艇”,我认为这又是一个漫长的过程。 – AOAOne 2012-04-18 14:39:48