How To Generate Combinations With None Values In A Progressive Manner
I want to generate combinations (with empty values) between multiple lists in a progressive manner. For example, a=[1,2,3], b=[4,5,6], the desired output should be [(1, None), (2,
Solution 1:
First let's take a look at what you are expecting :
What you want isn't C(6,3)=20.
Actually what you want is
C(3,i) * C(3,i) for i in [1,2,3] = 20
Why so ?
The first choice is the number of not None in your tuples, the second is the choices for the values you want to pick in those.
I'm trying to figure out a way to do this. But just wanted to explain the math so everyone is on the same page
import itertools as it
from copy import deepcopy
a = [1,2,3]
b = [4,5,6]
defcreate_combos(a, l):
n = len(a)
incr = 0
output = []
default = [[x,None] for x in a]
for i inrange(n+1):
choices_index = it.combinations(range(n),i)
choices_value = list(it.combinations(l,i))
for choice in choices_index:
for values in choices_value:
x = deepcopy(default)
for index,value inzip(choice,values):
x[index][1] = value
output += [x]
print(len(output))
print(output)
create_combos(a,b)
Okay now I have the same output as you , let's try to figure out a way to optimise this thing.
Solution 2:
If the order is not important, it should be possible to do with itertools.combinations
:
A (somehat long) one-liner is:
from itertools import combinations
combo_gen = ([(1, a), (2, b), (3, c)]
for a, b, c in combinations([None,4,None,5,None,6], 3))
Here every second element picked is None
thereby allowing all types of None
-interspersion.
Post a Comment for "How To Generate Combinations With None Values In A Progressive Manner"