combinations of an integer list with product limit
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.