0

I am trying to solve a Problem with the itertools module in Python. Unfortunately I couldn't solve it and I am looking for help here

Imagine we want to make a experiment, and we have 4 diffrent factors named:

[a,b,c,d]

Each of the factors can be changed around 3 different values for example:

a=[a1=10,a2=20,a3=30]

Now to see what the impact of the changed factor is I want only to change one value by one.

How can I get a list of all possible combinations?

So for this small example I am searching to create the following table:

    [[a1,b1,c1,d1]
     [a1,b1,c1,d2]
     [a1,b1,c1,d3]
     [a1,b1,c1,d4]
     [a1,b1,c2,d1]
     [a1,b1,c3,d1]
     [a1,b1,c4,d1]
     [a1,b2,c1,d1]
     [a1,b3,c1,d1]
     [a1,b4,c1,d1]
     [a2,b1,c1,d1]
     [a3,b1,c1,d1]
                 ]
Phil-_-
  • 23
  • 6

1 Answers1

1

This doesn't need itertools; just use a nested loop. The outer loop selects which factor to vary, and the inner loop varies it over its possible values. The input format is a list of lists, where each "row" contains the possible values for one factor, the first value being its "default".

def vary_individual_factors(factors):
    r = [f[0] for f in factors]
    yield tuple(r)
    for i, [first, *rest] in enumerate(factors):
        for x in rest:
            r[i] = x
            yield tuple(r)
        r[i] = first

Example:

>>> factors = [
...     ['a1', 'a2', 'a3', 'a4'],
...     ['b1', 'b2', 'b3', 'b4'],
...     ['c1', 'c2', 'c3', 'c4'],
...     ['d1', 'd2', 'd3', 'd4']
... ]
... 
>>> for t in vary_individual_factors(factors):
...     print(t)
... 
('a1', 'b1', 'c1', 'd1')
('a2', 'b1', 'c1', 'd1')
('a3', 'b1', 'c1', 'd1')
('a4', 'b1', 'c1', 'd1')
('a1', 'b2', 'c1', 'd1')
('a1', 'b3', 'c1', 'd1')
('a1', 'b4', 'c1', 'd1')
('a1', 'b1', 'c2', 'd1')
('a1', 'b1', 'c3', 'd1')
('a1', 'b1', 'c4', 'd1')
('a1', 'b1', 'c1', 'd2')
('a1', 'b1', 'c1', 'd3')
('a1', 'b1', 'c1', 'd4')
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • Thank you @kaya3! This works very well, works perfect for my problem! Really thought before I am on a good way with the itertools model but seems like not.. Thanks a lot! – Phil-_- Feb 05 '20 at 23:20