combinations of an integer list with product limit In python the itertools module is a good tool to generate combinations of elements. In this case I want to generate all combinations (without repetition) having a subsets of specified length but also with a product limit. For example, given a list of integer numbers I want all subsets of length 4 which product is bellow a given numerical limit, like bellow:
import functools, operator
LST = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 ]
prod = lambda A : functools.reduce(operator.mul, A )

def combinations_with_limit( LST, length,lim ) : 
''':Description: LST - array of integers, 
    length = number of elements in each subset , 
    lim = product limit of each subset '''

    H = list(range(length))         # H - represents the index array
    B = [ LST[ii] for ii in H ]     # B - the main array with elements
    while H[0] &lt;= len(LST)-length  :
        for i in range( H[-1], len(LST)) :
            H = H[:-1] + [i]
            B = [ LST[ii] for ii in H ]
            if prod(B) &gt; lim :      ###  LIMIT THE OUTCOME PART . It skips the rest of the iteration
                H[-1] = len(LST) - 1
            elif prod(B) &lt;= lim :
                yield B
            if H[-1] == len(LST) - 1 :    # We reset the index array here
                j = len(H)-1
                while H[j] == len(LST)-length+j :
                    j -=1
                H[j] +=1
                for l in range(j+1, len(H)) :
                    H[l] = H[l-1] +1

for i in combinations_with_limit(LST, 4 , 1000 ) :
    print(i ,end='  ' )

The output will look as follows:
[2, 3, 5, 7]  [2, 3, 5, 11]  [2, 3, 5, 13]  [2, 3, 5, 17]  [2, 3, 5, 19] 
[2, 3, 5, 23]  [2, 3, 5, 29]  [2, 3, 5, 31]  [2, 3, 7, 11]  [2, 3, 7, 13]  
[2, 3, 7, 17]  [2, 3, 7, 19]  [2, 3, 7, 23]  [2, 5, 7, 11]  [2, 5, 7, 13] 

And this is correct. All the products subsets are bellow the requested limit. However, I think that the above code is non-elegant and has some major loop inefficiency as I tested it for larger lists with &gt; thousands of elements.
Do you have any ideas on how to improve it?
Welcome to Python programming!

Your code has various formatting issues, including the fact that when copying it here, you messed up the indentation of the docstring in your function – copying what you write here into my development environment will not work because of that. But let's look at the semantics.

On a high level view, this sounds like a problem I would try to solve recursively.

All the products of one number that are less than or equal to a target (you don't state that equal-to is permitted, but the line if prod(B) &gt; lim : makes me think that is what you want) are exactly the numbers n &lt;= limit, and from there we can generalize to implementing ‘The product of k numbers ≤ p if x is the first number and the product of the remaining k-1 numbers ≤ p//x.’ Note that this works with integer division – If you allow floats or if your limit is exclusive, you need float division.

For that recursive solution, I would use a generator and yield every partial solution up the call chain until I get to the original loop that wants my results.

But let us assume that, for whatever reason, you indeed want a function that solves this iteratively, not recursively.

Then, even before I look at your function, it has issue: 2*3*11*13 = 858 &lt; 1000, but that combination does not appear in your list, so you would do well trying to manually generate maybe two examples where you know the answer, and try to produce them using your function.

If you feel it difficult to use the mental arithmetics, trust the tools you mention:

def combinations_with_limit(lst, length, lim):
    return [x for x in itertools.combinations(lst, length)
            if prod(x) &lt;= lim]


is quite a readable and explicit process. It might throw away a lot of things, but it should help you get test cases.

Once you have a working solution, there are several things in your code to look out for.


Calculating the product separately for various combinations, and even twice in your middle loop, will be expensive. Store it somewhere and manipulate it while moving about, instead of running prod too often, in particular if you have a need to access it twice, like in your if and elif.
You are manipulating both H and B in parallel. That feels dangerous: You need great care to make sure that H goes through all combinations, keeping the right length, and never gains any duplicate elements, and then you add the computational overhead of a full list comprehension on top to generate your Bs. That sounds easy to get wrong, and as your results show, one of the conditions indeed goes wrong.