1

I have a function that has a following signature:

def function(a=None, b=None, c=None):
    # ... some more code ... 

If passed, a, b and c can only be booleans.

I want to know all the valid combinations of a, b and c.

Note that a, b and c are optional, so this function can be called with as little as 0 parameters and as much as 3 parameters.

I'm able to get all the possible argument combinations:

arg_names = ['a', 'b', 'c']
arg_values = [None, True, False]

arg_combinations = []
for i in range(len(arg_names)):
    arg_combinations += list(
        itertools.combinations(arg_names, i + 1)
    )

Which produces:

[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]

However I'm not able to move further, creating all possible combinations of parameters and values:

arg_value_combinations = []
for c in arg_combinations:
    arg_value_combinations += list(
        itertools.product(c, arg_values)
    )

print arg_value_combinations

Which produces:

[('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False), ('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('a', None), ('a', True), ('a', False), ('c', None), ('c', True), ('c', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False), ('a', None), ('a', True), ('a', False), ('b', None), ('b', True), ('b', False), ('c', None), ('c', True), ('c', False)]

Definitely wrong path.

Peter Kilczuk
  • 589
  • 2
  • 7
  • 19

1 Answers1

5

If each value can hold None, False or True, simply produce those combinations (with itertools.product() , and filter out the elements that picked None:

from itertools import product

for combo in product((None, True, False), repeat=3):
    arguments = {k: v for k, v in zip('abc', combo) if v is not None}
    print arguments

This produces:

>>> from itertools import product
>>> for combo in product((None, True, False), repeat=3):
...     arguments = {k: v for k, v in zip('abc', combo) if v is not None}
...     print arguments
... 
{}
{'c': True}
{'c': False}
{'b': True}
{'c': True, 'b': True}
{'c': False, 'b': True}
{'b': False}
{'c': True, 'b': False}
{'c': False, 'b': False}
{'a': True}
{'a': True, 'c': True}
{'a': True, 'c': False}
{'a': True, 'b': True}
{'a': True, 'c': True, 'b': True}
{'a': True, 'c': False, 'b': True}
{'a': True, 'b': False}
{'a': True, 'c': True, 'b': False}
{'a': True, 'c': False, 'b': False}
{'a': False}
{'a': False, 'c': True}
{'a': False, 'c': False}
{'a': False, 'b': True}
{'a': False, 'c': True, 'b': True}
{'a': False, 'c': False, 'b': True}
{'a': False, 'b': False}
{'a': False, 'c': True, 'b': False}
{'a': False, 'c': False, 'b': False}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343