The problem I'm trying to solve is to get the set S which holds all the possible permutations of X number of integers such that all the integers are greater than 0 and when added are equal to some Y.
So, if X were equal to 2 and Y were equal to 5, the problem could be solved with this list comprehension:
[(a,b) for a in range(1,5) for b in range(1,5) if a+b==5]
However, I'm trying to solve for an arbitrary X and an arbitrary Y. I could write this as a gigantic series of if statements, but I feel like I'm so close to a nice, clean list comprehension to handle it. Is there any way to do this with list comprehensions?
Something like that:
[x for x in itertools.product(*variables) if sum(x)==5]
where variables is a list/tuple of your ranges
Sure. But you'll need sum() and itertools.product().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With