Reputation: 197
I am trying to generate a list of ordered pairs with replacement (i.e. needs (0.1, 0.1)
, (0.1, 0.2)
and (0.2, 0.1)
)that fulfil the condition that their sum is <= max_sum
in Python. For example, given max_sum=1
and the list:
[0, 0.1, 0.2, ..., 0.9, 1.0]
I'd like to produce a list containing:
[(0, 0), (0, 0.1), ..., (0, 0.9), (0, 1.0), (0.1, 0), (0.1, 0.1), ..., (0.1, 0.8), (0.1, 0.9), (0.2, 0), (0.2, 0.1), ...]
but not (0.1, 1.0)
etc.
Here is a likely inefficient and ugly solution that has some issues in that the if statement sometimes doesn't resolve correctly:
alphas = [0., .1, .2, .3, .4, .5, .6, .7, .8, .9, 1.]
max_sum = 1
def get_pairs(alphas, max_sum)
for a in alphas:
for b in alphas:
if a + b <= max_sum:
yield (a, b)
Upvotes: 1
Views: 1134
Reputation: 771
You can use itertools permutations. Example code.
from itertools import permutations
test_list = [0, 0.1, 0.2, 0.9, 1.0]
final_list = [item for item in permutations(test_list,2) if sum(item)<=1]
print(final_list)
[(0, 0.1), (0, 0.2), (0, 0.9), (0, 1.0), (0.1, 0), (0.1, 0.2), (0.1, 0.9), (0.2, 0), (0.2, 0.1), (0.9, 0), (0.9, 0.1), (1.0, 0)]
Upvotes: 1
Reputation: 2133
If order matters, which means you will have both (0, 0.2)
and (0.2,0)
for example, then you can try this :
L = [round(x*0.1, 2) for x in range(0, 10)]
print([(x,y) for x in L for y in L if x + y <= 1])
Output :
[(0.0, 0.0), (0.0, 0.1), (0.0, 0.2), ... (0.8, 0.2), (0.9, 0.0), (0.9, 0.1)]
Upvotes: 3
Reputation: 1777
Something like this:
import itertools
everyPermutation = [x for x in itertools.permutations(iterable, 2)]
finalList = [[x,y] for x,y in everyPermutation if (x + y) <= 1]
Upvotes: 1