Last active
June 30, 2020 17:42
-
-
Save benjaminaaron/543ed80031a4c9a92ef612cffec65d8b to your computer and use it in GitHub Desktop.
Generate all combinations based on a combination of mandatory and optional parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: