Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehensions with arbitrary numbers of variables in Python?

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?

like image 728
Evan Rose Avatar asked Jan 28 '26 08:01

Evan Rose


2 Answers

Something like that:

[x for x in itertools.product(*variables) if sum(x)==5]

where variables is a list/tuple of your ranges

like image 111
JBernardo Avatar answered Jan 29 '26 21:01

JBernardo


Sure. But you'll need sum() and itertools.product().

like image 27
Ignacio Vazquez-Abrams Avatar answered Jan 29 '26 21:01

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!