I have a list of tuples, which essentially are ranges my ith value can iterate in. The list looks like the one below:
L = [(10,20),(30,40),(60,70),(90,100)]
These are the upper and lower bounds of these ranges and will be fixed before generating all values where the bounds are inclusive.
Can someone tell me what is the best way to generate unique combination where each value of the list lies between its tuple bounds? 14641 combinations.
Ex:
[15,30,65,90] is valid
[27,33,67,99] is not valid
I tried using for loops by nesting them but ran into issues with runtime.
Any help is appreciated. Thanks a lot.
CodePudding user response:
The following will do, using itertools.product
:
from itertools import product
combos = product(*(range(a, b 1) for a, b in L))
next(combos)
# (10, 30, 60, 90)
next(combos)
# (10, 30, 60, 91)
# ...
If you need them in a list
, just unpack the iterator:
combos = [*product(*(range(a, b 1) for a, b in L))]
CodePudding user response:
Use itertools.product
and itertools.starmap
to map range over the intervals.
from itertools import product, starmap
L = [(10, 20), (30, 40), (60, 70), (90, 100)]
Ls = [(lb, ub 1) for lb, ub in L]
for combination in product(*starmap(range, L)):
print(combination)
CodePudding user response:
You could use:
from itertools import product
L = [(10,20),(30,40),(60,70),(90,100)]
L2 = [list(range(a, b 1)) for a,b in L]
all_products = list(itertools.product(*L2))
Getting random values:
import random
random.sample(all_products, 10)
output:
[(12, 37, 61, 98),
(15, 35, 65, 90),
(13, 38, 61, 98),
(12, 37, 61, 92),
(19, 34, 63, 91),
(15, 37, 66, 91),
(13, 32, 66, 98),
(17, 31, 64, 97),
(10, 38, 63, 99),
(16, 34, 61, 90)]