Skip to content

Instantly share code, notes, and snippets.

@benjaminaaron
Last active June 30, 2020 17:42
Show Gist options
  • Save benjaminaaron/543ed80031a4c9a92ef612cffec65d8b to your computer and use it in GitHub Desktop.
Save benjaminaaron/543ed80031a4c9a92ef612cffec65d8b to your computer and use it in GitHub Desktop.
Generate all combinations based on a combination of mandatory and optional parts
import numpy as np
line = "mandatory1(optional1)mandatory2(optional2)(optional3)"
# use regex or a char by char stack approach to extract these?
parts = ["mandatory1", "optional1", "mandatory2", "optional2", "optional3"]
fixPositions = [0, 2]
elements = len(parts)
optionalElements = elements - len(fixPositions)
n = 2 ** optionalElements
print(elements, "elements in total:", len(fixPositions), "fix,", optionalElements, "optional --> generating", n, "options")
# via https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-187.php
matrix = (((np.arange(n).reshape(-1, 1) & (2 ** np.arange(optionalElements))) != 0).astype(int))[:, ::-1]
for fixPos in fixPositions:
insertCol = np.full((n, 1), 1)
# via https://stackoverflow.com/a/40825989, use pandas instead?
matrix = np.hstack((matrix[:, :fixPos], insertCol, matrix[:, fixPos:]))
# print(matrix)
for r in range(n):
row = matrix[r]
branch = []
for c in range(elements):
if row[c] == 1:
branch.append(parts[c])
print(branch)
@benjaminaaron
Copy link
Author

Output:

['mandatory1', 'mandatory2']
['mandatory1', 'mandatory2', 'optional3']
['mandatory1', 'mandatory2', 'optional2']
['mandatory1', 'mandatory2', 'optional2', 'optional3']
['mandatory1', 'optional1', 'mandatory2']
['mandatory1', 'optional1', 'mandatory2', 'optional3']
['mandatory1', 'optional1', 'mandatory2', 'optional2']
['mandatory1', 'optional1', 'mandatory2', 'optional2', 'optional3']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment