Dynamically brute-force all numerical combinations

Advertisements

As the title says I’m trying to get all possible numerical combinations for an unknown number of parameters. I don’t mind if you use pandas or numpy. See the code section to understand my problem easily. Any help would be appreciated.

# n can be any integer. 4 is just an example.
n = 4 
possibleValues = range(1, n+1)
# [1, 2, 3, 4]

# The number of elements in this list is unknown. It's only 2 elements just for example
parameters = ["foo", "boo"]

Expected results:
{'foo': 1, 'boo': 1},
{'foo': 1, 'boo': 2},
{'foo': 1, 'boo': 3},
{'foo': 1, 'boo': 4},

{'foo': 2, 'boo': 1},
{'foo': 2, 'boo': 2},
{'foo': 2, 'boo': 3},
{'foo': 2, 'boo': 4}

...

{'foo': 4, 'boo': 1},
{'foo': 4, 'boo': 2},
{'foo': 4, 'boo': 3},
{'foo': 4, 'boo': 4}

>Solution :

itertools.product() will do this for you. You need to tell it how many to repeat, which in this case is the length of the dict keys. Then just zip them up and pass to dict():

from itertools import product

n = 4 
possibleValues = range(1, n+1)
parameters = ["foo", "boo"]

[dict(zip(parameters, pair)) for pair in product(possibleValues, repeat=len(parameters))]

Which gives you:

[{'foo': 1, 'boo': 1},
 {'foo': 1, 'boo': 2},
 {'foo': 1, 'boo': 3},
 {'foo': 1, 'boo': 4},
 {'foo': 2, 'boo': 1},
 {'foo': 2, 'boo': 2},
 {'foo': 2, 'boo': 3},
 {'foo': 2, 'boo': 4},
 {'foo': 3, 'boo': 1},
 {'foo': 3, 'boo': 2},
 {'foo': 3, 'boo': 3},
 {'foo': 3, 'boo': 4},
 {'foo': 4, 'boo': 1},
 {'foo': 4, 'boo': 2},
 {'foo': 4, 'boo': 3},
 {'foo': 4, 'boo': 4}]

Leave a ReplyCancel reply