(First, I chose to do this in Python because I never programmed in it and it would be good practice.)
Someone asked me to implement a little "combination" program that basically outputs all possible combinations of a set of group of numbers. Example, if you have:
(1,2,3) as the first set,
(4,5,6) as the second, and
(7,8,9) as the third, then one combination would be (1,4,7) and so on, with a total of 27 possible combinations.
This person just wants to do a 6rows x 6cols matrix or a 5rows x 6cols matrix. However, I want to make my little program as flexible as possible.
The next requirement is to only output combinations with X even numbers. If he wants 0 even numbers, then a possible combination would be (1,5,7). You get the idea.
For the permutation part, I used itertools.product(), which works perfectly.
It would be easy if I just assume that the number of numbers in each set (cols) is fixed as 6.
In that case, I could manually create 6 lists and append each combination to the right list.
However and again, I want this to work with N number of cols.
I'm thinking of 2 ways I might be able to do this, but tried with no luck.
So my question is:
How can I create?
li_1 = []
li_2 = []
...
li_x = []
The one way I tried using "lists of lists":
for combination in itertools.product(*li):
total_combinations = total_combinations + 1
#Counts number of even numbers in a single combination
for x in range(numberInRows):
if combination[x] % 2 == 0:
even_counter = even_counter + 1
print "Even counter:",even_counter
num_evens[even_counter].append(combination)
print "Single set:",num_evens
even_counter = 0
print combination
print "Num_evens:",num_evens
print '\nTotal combinations:', total_combinations