Possible Duplicate:
Finding all possible combinations of numbers to reach a given sum
I don't want to use Itertools because it outputs things in an order I don't want and can't use (I need to be able to evaluate what the combination generator is trying to output to decide if I want to keep going down that branch).
For instance, let's say I have a list [1,2,3,4,5] and I want to output combinations that have a full-product <=12 without wasting iterations. If I generate, say, [1,2,3], this is fine because 1*2*3=6. But if I try [1,2,3,4] then 1*2*3*4=24, and this is greater than 12, and therefore I shouldn't even bother looking into [1,2,3,5] or [1,2,4,5] and so on.
Current attempt:
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
Where am I going wrong?