Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically brute-force all numerical combinations

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading